<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description">
<meta property="og:type" content="website">
<meta property="og:title" content="Hexo">
<meta property="og:url" content="http://yoursite.com/page/13/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hexo">
<meta name="twitter:description">
  
    <link rel="alternative" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  

</head>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main">
  
    <article id="post-mybatis/1.Mybatis系列之入门" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/09/mybatis/1.Mybatis系列之入门/" class="article-date">
  <time datetime="2015-12-09T04:00:00.000Z" itemprop="datePublished">2015-12-09</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/mybatis/">mybatis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/09/mybatis/1.Mybatis系列之入门/">Mybatis系列一之入门</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u6982_u8FF0"><a href="#u6982_u8FF0" class="headerlink" title="概述"></a>概述</h2><p>　　作为一个半自动化的orm框架，相较于hibernate等，mybatis在互联网企业中有更加广泛的使用。下面我们搭建一个示例进行快速入门。</p>
<h2 id="u6DFB_u52A0_u4F9D_u8D56pom-xml"><a href="#u6DFB_u52A0_u4F9D_u8D56pom-xml" class="headerlink" title="添加依赖pom.xml"></a>添加依赖pom.xml</h2><p>　　新建一个maven工程，添加必要的jar包，如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>org.mybatis<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>mybatis<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">version</span>&gt;</span>3.3.0<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">version</span>&gt;</span>5.1.34<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">version</span>&gt;</span>1.2.16<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">version</span>&gt;</span>4.11<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="title">scope</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<h2 id="u914D_u7F6EMybatis"><a href="#u914D_u7F6EMybatis" class="headerlink" title="配置Mybatis"></a>配置Mybatis</h2><p>　　新建配置文件mybatis-conf.xml文件如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="doctype">&lt;!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">configuration</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 指定properties配置文件， 我这里面配置的是数据库相关 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">properties</span> <span class="attribute">resource</span>=<span class="value">"dbConfig.properties"</span>&gt;</span><span class="tag">&lt;/<span class="title">properties</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 指定Mybatis使用log4j --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">settings</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">setting</span> <span class="attribute">name</span>=<span class="value">"logImpl"</span> <span class="attribute">value</span>=<span class="value">"LOG4J"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">settings</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="title">environments</span> <span class="attribute">default</span>=<span class="value">"development"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">environment</span> <span class="attribute">id</span>=<span class="value">"development"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">transactionManager</span> <span class="attribute">type</span>=<span class="value">"JDBC"</span> /&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- 配置数据库连接信息 --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">dataSource</span> <span class="attribute">type</span>=<span class="value">"POOLED"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"driver"</span> <span class="attribute">value</span>=<span class="value">"com.mysql.jdbc.Driver"</span> /&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"url"</span> <span class="attribute">value</span>=<span class="value">"jdbc:mysql://localhost:3306/mybatis"</span> /&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"username"</span> <span class="attribute">value</span>=<span class="value">"root"</span> /&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"password"</span> <span class="attribute">value</span>=<span class="value">"123456"</span> /&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="title">dataSource</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">environment</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">environments</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="title">mappers</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 注册userMapper.xml文件--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">mapper</span> <span class="attribute">resource</span>=<span class="value">"com/openim/test/mybatis/mapper/userMapper.xml"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">mappers</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<h2 id="u7F16_u5199_u7C7BUser"><a href="#u7F16_u5199_u7C7BUser" class="headerlink" title="编写类User"></a>编写类User</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">    <span class="comment">//实体类的属性和表的字段名称一一对应</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> age;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(<span class="keyword">int</span> id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getAge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAge</span><span class="params">(<span class="keyword">int</span> age)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"User [id="</span> + id + <span class="string">", name="</span> + name + <span class="string">", age="</span> + age + <span class="string">"]"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="u65B0_u5EFA_u6570_u636E_u5E93"><a href="#u65B0_u5EFA_u6570_u636E_u5E93" class="headerlink" title="新建数据库"></a>新建数据库</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="operator"><span class="keyword">create</span> <span class="keyword">database</span> mybatis;</span></span><br><span class="line"><span class="operator"><span class="keyword">use</span> mybatis;</span></span><br><span class="line"><span class="operator"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="keyword">users</span>(<span class="keyword">id</span> <span class="built_in">INT</span> PRIMARY <span class="keyword">KEY</span> AUTO_INCREMENT, <span class="keyword">NAME</span> <span class="built_in">VARCHAR</span>(<span class="number">20</span>), age <span class="built_in">INT</span>);</span></span><br><span class="line"><span class="operator"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="keyword">users</span>(<span class="keyword">NAME</span>, age) <span class="keyword">VALUES</span>(<span class="string">'金木'</span>, <span class="number">20</span>);</span></span><br><span class="line"><span class="operator"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="keyword">users</span>(<span class="keyword">NAME</span>, age) <span class="keyword">VALUES</span>(<span class="string">'水火'</span>, <span class="number">20</span>);</span></span><br></pre></td></tr></table></figure>
<h2 id="u7F16_u5199mapper-xml"><a href="#u7F16_u5199mapper-xml" class="headerlink" title="编写mapper.xml"></a>编写mapper.xml</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="doctype">&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 为这个mapper指定一个唯一的namespace，namespace的值习惯上设置成包名+sql映射文件名，这样就能够保证namespace的值是唯一的--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">mapper</span> <span class="attribute">namespace</span>=<span class="value">"com.openim.test.mybatis.mapper.userMapper"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--&lt;cache type="org.mybatis.caches.ehcache.EhcacheCache"/&gt;--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">select</span> <span class="attribute">id</span>=<span class="value">"getUser"</span> <span class="attribute">parameterType</span>=<span class="value">"int"</span> <span class="attribute">resultType</span>=<span class="value">"com.openim.test.mybatis.model.User"</span>&gt;</span></span><br><span class="line">        select * from users where id=#&#123;id&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="title">select</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="u7F16_u5199_u6D4B_u8BD5_u7C7B"><a href="#u7F16_u5199_u6D4B_u8BD5_u7C7B" class="headerlink" title="编写测试类"></a>编写测试类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span></span>&#123;</span><br><span class="line">    String resource = <span class="string">"mybatis-conf.xml"</span>;</span><br><span class="line">    <span class="comment">//使用类加载器加载mybatis的配置文件（它也加载关联的映射文件）</span></span><br><span class="line">    InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);</span><br><span class="line">    <span class="comment">//构建sqlSession的工厂</span></span><br><span class="line">    SqlSessionFactory sessionFactory = <span class="keyword">new</span> SqlSessionFactoryBuilder().build(is);</span><br><span class="line">    <span class="comment">//使用MyBatis提供的Resources类加载mybatis的配置文件（它也加载关联的映射文件）</span></span><br><span class="line">    <span class="comment">//Reader reader = Resources.getResourceAsReader(resource);</span></span><br><span class="line">    <span class="comment">//构建sqlSession的工厂</span></span><br><span class="line">    <span class="comment">//SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);</span></span><br><span class="line">    <span class="comment">//创建能执行映射文件中sql的sqlSession</span></span><br><span class="line">    SqlSession session = sessionFactory.openSession();</span><br><span class="line">    <span class="comment">/**</span><br><span class="line">     * 映射sql的标识字符串，</span><br><span class="line">     * com.openim.test.mybatis.mapper.userMapper是userMapper.xml文件中mapper标签的namespace属性的值，</span><br><span class="line">     * getUser是select标签的id属性值，通过select标签的id属性值就可以找到要执行的SQL</span><br><span class="line">     */</span></span><br><span class="line">    String statement = <span class="string">"com.openim.test.mybatis.mapper.userMapper.getUser"</span>;<span class="comment">//映射sql的标识字符串</span></span><br><span class="line">    User user = session.selectOne(statement, <span class="number">1</span>);</span><br><span class="line">    System.out.println(user);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>　　到这里，入门环境便搭建好了，直接运行即可。下面一篇文章开始根据该示例代码深入源码进行分析！！！</p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p>动态SQL语句：<a href="http://limingnihao.iteye.com/blog/782190" target="_blank" rel="external">http://limingnihao.iteye.com/blog/782190</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/09/mybatis/1.Mybatis系列之入门/" data-id="cijzzpv9c00801cfsdjbnaxda" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mybatis/">mybatis</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-nodejs/1.NodeJS系列之概述" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/08/nodejs/1.NodeJS系列之概述/" class="article-date">
  <time datetime="2015-12-07T17:00:00.000Z" itemprop="datePublished">2015-12-08</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/nodejs/">nodejs</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/08/nodejs/1.NodeJS系列之概述/">NodeJS系列一之概述</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　NodeJS使用事件驱动的、非阻塞的I/O模型，这让其既轻量又高效，是运行于不同发布设备上的数据密集型实时应用程序的完美平台。它不适合处理包含大量数据或者长时间运行计算等，旨在网络中推送数据并瞬间完成。适合于高并发、聊天、实时消息推送（socket.io，兼容不同浏览器）等场景</p>
<h2 id="windows_u7248_u672C_u5B89_u88C5"><a href="#windows_u7248_u672C_u5B89_u88C5" class="headerlink" title="windows版本安装"></a>windows版本安装</h2><p>　　待补充<br>　　注意：windows下安装nodejs时，如果改变了默认的安装路径，则在用npm install时，会出现错误：nodejs/windows Error: ENOENT, stat ‘C:\Users\***\AppData\Roaming\npm’。只需手动在C:\Users\***\AppData\Roaming\目录下建立 npm 文件夹</p>
<h2 id="linux_u7248_u672C_u5B89_u88C5"><a href="#linux_u7248_u672C_u5B89_u88C5" class="headerlink" title="linux版本安装"></a>linux版本安装</h2><p>　　待补充</p>
<h2 id="u793A_u4F8B"><a href="#u793A_u4F8B" class="headerlink" title="示例"></a>示例</h2><p>　　新建文件01/server.js，输入如下代码<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line">http.createServer(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>)</span>&#123;</span><br><span class="line">    res.writeHead(<span class="number">200</span>, &#123;<span class="string">'Content-Type'</span>:<span class="string">'text/plain'</span>&#125;);</span><br><span class="line">    res.end(<span class="string">"Hello World"</span>);</span><br><span class="line">&#125;).listen(<span class="number">3000</span>, <span class="string">"127.0.0.1"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'server running at http://127.0.0.1:3000'</span>);</span><br></pre></td></tr></table></figure></p>
<p>　　在命令行中键入node server.js，启动服务。在浏览器中访问<a href="http://127.0.0.1:3000" target="_blank" rel="external">http://127.0.0.1:3000</a>即可看到结果</p>
<h2 id="npm"><a href="#npm" class="headerlink" title="npm"></a>npm</h2><p>　　npm: node package manager 包管理器。可以理解为java中maven对jar包的依赖管理。可以使用命令“npm install [module_name] ”向npm注册服务器发送请求，将某个模块的最新版本下载到计算机上。在NodeJs中使用模块方式：var module = require(‘module’);。下面我们以underscore模块为例。新建文件foo.js，并输入如下内容：<br>　　npm: node package manager 包管理器。可以理解为java中maven对jar包的依赖管理。可以使用命令“npm install [module_name] ”向npm注册服务器发送请求，将某个模块的最新版本下载到计算机上。在NodeJs中使用模块方式：var module = require(‘module’);。下面我们以underscore模块为例。新建文件foo.js，并输入如下内容：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> _ = <span class="built_in">require</span>(<span class="string">"underscore"</span>);</span><br><span class="line">_.each([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], <span class="function"><span class="keyword">function</span>(<span class="params">num</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"underscore.js says "</span> + num);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p>　　在命令行中输入 npm install underscore 下载underscore，再输入node foo.js执行。执行npm install后，会在相应的文件夹下会产生目录node_modules\underscore，即将underscore模块放到了目录node_modules下。上面<br>　　这种方式为<strong>本地安装</strong>，下载的模块只能被该项目使用，注意，这是最为常见并且推荐安装Node.js模块的方法。npm还支持<strong>全局安装</strong>的方式。只需在安装时加上-g标记，这意味着在文件系统的任何位置都可以运行模块，如：npm install -g express，此时express会安装到路径C:\Users\****\AppData\Roaming\npm\node_modules\express下。express是Node.js的一个Web开发框架。下面介绍一下npm的常用命令：<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">#卸载卸载全局</span><br><span class="line">npm uninstall -g express</span><br><span class="line"></span><br><span class="line">#找模块文档，此时会主动打开浏览器，跳转到express的主页</span><br><span class="line">npm docs express</span><br><span class="line"></span><br><span class="line">#查看项目的bug，也是在浏览器中打</span><br><span class="line">npm bugs express</span><br></pre></td></tr></table></figure></p>
<h2 id="package-json"><a href="#package-json" class="headerlink" title="package.json"></a>package.json</h2><p>　　使用package.json确定依赖关系（类似于maven的pom.xml文件），进入文件foo.js所在的目录，新建文件package.json，输入如下内容<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="string">"name"</span>: <span class="string">"foo"</span>, </span><br><span class="line">    <span class="string">"version"</span>: <span class="string">"0.0.1"</span>, </span><br><span class="line">    <span class="string">"dependencies"</span>: &#123;</span><br><span class="line">        <span class="string">"underscore"</span>: <span class="string">"1.7.0"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　终端输入 npm install ，注意，此时去掉了underscore，执行完毕后，会在目录下安装模块node_modules\underscore。社区中流行的模块查找地址：<a href="http://blago.dachev.com/modules" target="_blank" rel="external">http://blago.dachev.com/modules</a> 和 <a href="http://eirikb.github.io/nipster/" target="_blank" rel="external">http://eirikb.github.io/nipster/</a></p>
<h2 id="u91CD_u5B9A_u5411"><a href="#u91CD_u5B9A_u5411" class="headerlink" title="重定向"></a>重定向</h2><p>　　重定向的准则：1. 给客户发送301相应代码，告诉客户，资源已经移到另一个位置；2. 发送一个位置头（Location Header）告诉客户重定向到哪里<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line">http.createServer(<span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">    res.writeHead(<span class="number">301</span>, &#123;</span><br><span class="line">        <span class="string">'Location'</span>: <span class="string">'http://www.baidu.com'</span></span><br><span class="line">    &#125;);</span><br><span class="line">    res.end(<span class="string">"Hello World"</span>);</span><br><span class="line">&#125;).listen(<span class="number">3000</span>, <span class="string">"127.0.0.1"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'Server running at http://127.0.0.1:3000/'</span>);</span><br></pre></td></tr></table></figure></p>
<h2 id="u8DEF_u7531"><a href="#u8DEF_u7531" class="headerlink" title="路由"></a>路由</h2><p>　　指应用程序要响应的请求，例如：如果想展示一个位于/about-us的页面，就需要在应用程序中对这一请求设置一个路由。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"><span class="keyword">var</span> url = <span class="built_in">require</span>(<span class="string">"url"</span>);</span><br><span class="line"><span class="comment">/*</span><br><span class="line">http://example.com:1234/pathname?query-string</span><br><span class="line">hostname=example.com</span><br><span class="line">port=34</span><br><span class="line">pathname=/pathname</span><br><span class="line">*/</span></span><br><span class="line">http.createServer(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> pathname = url.parse(req.url).pathname;</span><br><span class="line">    <span class="keyword">if</span> (pathname === <span class="string">'/'</span>) &#123;</span><br><span class="line">        res.writeHead(<span class="number">200</span>, &#123;</span><br><span class="line">            <span class="string">'Context-Type'</span>: <span class="string">'text/plain'</span></span><br><span class="line">        &#125;);</span><br><span class="line">        res.end(<span class="string">'Home Page'</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (pathname === <span class="string">'/about'</span>) &#123;</span><br><span class="line">        res.writeHead(<span class="number">200</span>, &#123;</span><br><span class="line">            <span class="string">'Context-Type'</span>: <span class="string">'text/plain'</span></span><br><span class="line">        &#125;);</span><br><span class="line">        res.end(<span class="string">'About us'</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (pathname === <span class="string">'/redirect'</span>) &#123;</span><br><span class="line">        res.writeHead(<span class="number">301</span>, &#123;</span><br><span class="line">            <span class="string">'Location'</span>: <span class="string">'/'</span></span><br><span class="line">        &#125;);</span><br><span class="line">        res.end();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        res.writeHead(<span class="number">404</span>, &#123;</span><br><span class="line">            <span class="string">'Context-Type'</span>: <span class="string">'text/plain'</span></span><br><span class="line">        &#125;);</span><br><span class="line">        res.end(<span class="string">"Page not found"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;).listen(<span class="number">3000</span>, <span class="string">"127.0.0.1"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'http://127.0.0.1:3000'</span>);</span><br></pre></td></tr></table></figure></p>
<h2 id="http_u5934"><a href="#http_u5934" class="headerlink" title="http头"></a>http头</h2><p>　　我们可以在Http头中发送大量信息，包括可接受的字符集，特权授权证书，日期以及用户代理等。Connection:Keep-Alive头让客户端与服务器可以一直打开持久连接，这会启用客户端和服务器之间的实时通信。</p>
<h2 id="u6587_u4EF6_u64CD_u4F5C"><a href="#u6587_u4EF6_u64CD_u4F5C" class="headerlink" title="文件操作"></a>文件操作</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1.读文件</span></span><br><span class="line"><span class="comment">//文件路径不是相对于writefile.js路径，</span></span><br><span class="line"><span class="comment">//而是相对于在终端中输入npm writefile时所在的路径</span></span><br><span class="line"><span class="comment">//或者指定完整的路径</span></span><br><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line">fs.readFile(<span class="string">'file.txt'</span>, <span class="string">'utf8'</span>,</span><br><span class="line"><span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!err) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(data);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">throw</span> err;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//2.写文件</span></span><br><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>),</span><br><span class="line">data = <span class="string">"Some data I want to write to a file"</span>;</span><br><span class="line"><span class="comment">//文件路径不是相对于writefile.js路径，</span></span><br><span class="line"><span class="comment">//而是相对于在终端中输入npm writefile时所在的路径</span></span><br><span class="line"><span class="comment">//或者指定完整的路径</span></span><br><span class="line"><span class="comment">/**</span><br><span class="line">writeFile方法会自动生成文件</span><br><span class="line">*/</span></span><br><span class="line">fs.writeFile(<span class="string">'file.txt'</span>, data,</span><br><span class="line"><span class="function"><span class="keyword">function</span>(<span class="params">err</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!err) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'Wrote data to file.txt'</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">throw</span> err;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="u8BFB_u53D6_u73AF_u5883_u53D8_u91CF"><a href="#u8BFB_u53D6_u73AF_u5883_u53D8_u91CF" class="headerlink" title="读取环境变量"></a>读取环境变量</h2><p>　　1.在终端中运行set something=’123456’。注意，等号两边不能有空格，linux下，set替换为export<br>　　2.新建文件environment.js，输入console.log(process.env.something2)<br>　　3.在终端中执行node environment，屏幕输出123456</p>
<h2 id="u64CD_u4F5Cmysql"><a href="#u64CD_u4F5Cmysql" class="headerlink" title="操作mysql"></a>操作mysql</h2><p>　　查看mysql包的使用文档，终端输入npm doc mysql，此时浏览器打开地址<a href="https://github.com/felixge/node-mysql" target="_blank" rel="external">https://github.com/felixge/node-mysql</a>，其中包括如何以连接池的方式打开和集群的方式，注意不同版本的mysql驱动，下面的写法也会发生变化<br>　　1. 新建mysql-test.js，输入如下内容<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mysql = <span class="built_in">require</span>(<span class="string">'mysql'</span>);</span><br><span class="line"><span class="keyword">var</span> connection = mysql.createConnection(&#123;</span><br><span class="line">    host: <span class="string">'localhost'</span>,</span><br><span class="line">    user: <span class="string">'root'</span>,</span><br><span class="line">    password: <span class="string">'123456'</span>,</span><br><span class="line">    database: <span class="string">'test'</span></span><br><span class="line">&#125;);</span><br><span class="line">connection.connect();</span><br><span class="line">connection.query(<span class="string">'SELECT 1 + 1 AS solution'</span>,</span><br><span class="line"><span class="function"><span class="keyword">function</span>(<span class="params">err, rows, fields</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'The solution is: '</span>, rows[<span class="number">0</span>].solution);</span><br><span class="line">&#125;);</span><br><span class="line">connection.query(<span class="string">'SELECT * from region'</span>,</span><br><span class="line"><span class="function"><span class="keyword">function</span>(<span class="params">err, rows, fields</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'The solution is: '</span>, rows);</span><br><span class="line">    <span class="comment">//console.log('The solution is: ', rows[0].solution);</span></span><br><span class="line">&#125;);</span><br><span class="line">connection.end();</span><br></pre></td></tr></table></figure></p>
<p>　　2. 新建package.json，输入如下内容<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="string">"name"</span>: <span class="string">"foo"</span>,</span><br><span class="line">    <span class="string">"version"</span>: <span class="string">"0.0.1"</span>,</span><br><span class="line">    <span class="string">"dependencies"</span>: &#123;</span><br><span class="line">        <span class="string">"mysql"</span>: <span class="string">"2.5.2"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　3. 安装mysql并运行<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install&#10;npm mysql-test</span><br></pre></td></tr></table></figure></p>
<p>　　4. 最后输出如下内容:<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">The solution is: 2</span><br><span class="line">The solution is: </span><br><span class="line">[&#123;</span><br><span class="line">    "idregion": 1, </span><br><span class="line">    "name": "中华人民共和国"</span><br><span class="line">&#125;, &#123;</span><br><span class="line">    "idregion": 2, </span><br><span class="line">    "name": "湖北省"</span><br><span class="line">&#125;,&#123;</span><br><span class="line">    "idregion": 3, </span><br><span class="line">    "name": "武汉市"</span><br><span class="line">&#125;, &#123;</span><br><span class="line">    "idregion": 4, </span><br><span class="line">    "name": "北京市"</span><br><span class="line">&#125;,&#123;</span><br><span class="line">    "idregion": 5, </span><br><span class="line">    "name": "中国共产党"</span><br><span class="line">&#125;,&#123;</span><br><span class="line">    "idregion": 6, </span><br><span class="line">    "name": "中国建设银行"</span><br><span class="line">&#125;,&#123;</span><br><span class="line">    "idregion": 7, </span><br><span class="line">    "name": "中国国家安全委员会"</span><br><span class="line">&#125;]</span><br></pre></td></tr></table></figure></p>
<h2 id="u64CD_u4F5CMongoDB"><a href="#u64CD_u4F5CMongoDB" class="headerlink" title="操作MongoDB"></a>操作MongoDB</h2><p>　　请在node.js入门经典第八章中查看<a href="https://github.com/LearnBoost/mongoose" target="_blank" rel="external">https://github.com/LearnBoost/mongoose</a></p>
<h2 id="Socket-IO"><a href="#Socket-IO" class="headerlink" title="Socket.IO"></a>Socket.IO</h2><p>　　Socket.IO是Node.js的一个模块，给应用程序加入对WebSocket的支持，也解决浏览器支持的问题。它既能在服务器，也能在客户端工作。使用时，必须将其添加到服务器端的JS和客户端的JS，这是因为通信是双向的，Socket.IO需要在两边工作。</p>
<h2 id="Grunt"><a href="#Grunt" class="headerlink" title="Grunt"></a>Grunt</h2><p>　　使用Grunt，可以很方便的定制各种任务，如压缩、合并等。使用Grunt之前，需要安装node环境和grunt工具。</p>
<h2 id="u6D4B_u8BD5"><a href="#u6D4B_u8BD5" class="headerlink" title="测试"></a>测试</h2><p>　　<strong>Assert</strong>模块，类似于junit中的assert，下面我们新建文件app.js，输入如下内容<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> assert = <span class="built_in">require</span>(<span class="string">'assert'</span>);</span><br><span class="line">assert.strictEqual(<span class="string">"hello"</span>, <span class="string">"hello"</span>);</span><br></pre></td></tr></table></figure></p>
<p>　　执行node app，此时终端不输出任何信息，表明测试通过<br>　　<strong>第三方测试工具</strong>，如Nodeunit、Vows、Mocha等功能更强大，输出html等格式，异步测试，处理测试的运行并报告结果等。全局安装 npm intall -g nodeunit 或者使用package.json文件来安装nodeunit，测试的模块通常在devDependencies中声明<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="string">"name"</span>: <span class="string">"nodeunit_example"</span>,</span><br><span class="line">    <span class="string">"version"</span>: <span class="string">"0.0.0"</span>,</span><br><span class="line">    <span class="string">"private"</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="string">"devDependencies"</span>: &#123;</span><br><span class="line">        <span class="string">"nodeunit"</span>: <span class="string">"0.8.2"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="string">``</span><span class="string">` javascript</span><br><span class="line">　　使用nodeunit的断言，注意：每个测试都声明成exports.testName</span><br><span class="line">`</span><span class="string">``</span> javascript</span><br><span class="line">exports.firstTest = <span class="function"><span class="keyword">function</span>(<span class="params">test</span>) </span>&#123;</span><br><span class="line">    test.expect(<span class="number">1</span>); <span class="comment">//开始出声明，参数为期望的断言数</span></span><br><span class="line">    test.strictEqual(<span class="string">"hello"</span>, <span class="string">"hello"</span>);</span><br><span class="line">    test.done();</span><br><span class="line">&#125;;</span><br><span class="line">exports.secondTest = <span class="function"><span class="keyword">function</span>(<span class="params">test</span>) </span>&#123;</span><br><span class="line">    test.expect(<span class="number">1</span>);</span><br><span class="line">    test.strictEqual(<span class="string">"hello"</span>, <span class="string">"there"</span>);</span><br><span class="line">    test.done();</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h2 id="supervisor"><a href="#supervisor" class="headerlink" title="supervisor"></a>supervisor</h2><p>　　使用supervisor，可以立刻在页面中看到修改结果<br>　　1. 安装supervisor，打卡cmd 输入npm install -g supervisor<br>　　2. 启动supervisor，supervisor hello.js<br>　　修改之前的hello.js内容，在网页中查看（此时需关闭之前启动的服务）<br>　　Node.js在调用某个包时，会首先检查包中package.json文件的main字段，将其作为包的接口模块，如果package.json或main字段不存在，会尝试寻找index.js或index.node作为包的接口</p>
<h2 id="Express"><a href="#Express" class="headerlink" title="Express"></a>Express</h2><p>　　Express是node.js的轻量级一个Web框架<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">#安装express</span><br><span class="line">npm install -g express</span><br><span class="line">#以上面这种方式安装的express，无法在终端中使用express命令，下面安装方式可以在express/README.md的文件中看到</span><br><span class="line">npm install -g express-generator@4</span><br><span class="line">#或者是</span><br><span class="line">npm install -g express-generator</span><br><span class="line"></span><br><span class="line">#根据README.md中的描述，进行如下操作</span><br><span class="line">npm install -g express-generator</span><br><span class="line">express /tmp/foo &amp;&amp; cd /tmp/foo</span><br><span class="line">npm install</span><br><span class="line">npm start</span><br><span class="line">#浏览器访问http://localhost:3000/即可</span><br><span class="line"></span><br><span class="line">#新建目录hello-world</span><br><span class="line">#在该目录下新建文件package.json，输入如下内容</span><br><span class="line">&#123;</span><br><span class="line">    "name": "hello-world", </span><br><span class="line">    "description": "hello world test app", </span><br><span class="line">    "version": "0.0.1", </span><br><span class="line">    "private": true, </span><br><span class="line">    "dependencies": &#123;</span><br><span class="line">        "express": "4.x"</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">#终端下进入目录hello-world执行npm intall，安装express</span><br><span class="line"></span><br><span class="line">#输入npm ls 以树形结构查看并显示其依赖项</span><br><span class="line">F:\GitRepository\nodejs\06\hello-world&gt;npm ls</span><br><span class="line">hello-world@0.0.1 F:\GitRepository\nodejs\06\hello-world</span><br><span class="line">└─┬ express@4.9.7</span><br><span class="line">  ├─┬ accepts@1.1.1</span><br><span class="line">  │ ├─┬ mime-types@2.0.2</span><br><span class="line">  ......</span><br><span class="line"></span><br><span class="line">#新建server.js文件，输入如下内容</span><br><span class="line">var express = require('express');</span><br><span class="line">var app = express();</span><br><span class="line">app.get('/',</span><br><span class="line">function(req, res) &#123;</span><br><span class="line">    res.send('Hello World!');</span><br><span class="line">&#125;);</span><br><span class="line">app.get('/about',</span><br><span class="line">function(req, res) &#123;</span><br><span class="line">    res.send('About!');</span><br><span class="line">&#125;);</span><br><span class="line">var server = app.listen(3000,</span><br><span class="line">function() &#123;</span><br><span class="line">    console.log('Listening on port %d', server.address().port);</span><br><span class="line">&#125;);</span><br><span class="line">#在浏览器中输入http://localhost:3000/查看结果</span><br><span class="line">#在输入http://localhost:3000/about查看结果</span><br><span class="line"></span><br><span class="line">#Express利用模板引擎将视图编译成html，默认情况下，express使用Jade作为模板引擎</span><br><span class="line">#安装jade</span><br><span class="line">npm install jade --save</span><br></pre></td></tr></table></figure></p>
<h2 id="u8C03_u8BD5"><a href="#u8C03_u8BD5" class="headerlink" title="调试"></a>调试</h2><p>　　nodejs核心带有STDIO模块，这是调试应用程序的一种轻量级放方法，直接在代码中添加console.log(“<em>*</em>‘)，亦可以使用console.error();。基准测试，探索代码的瓶颈所在或者想快速检测代码的某些部分的性能基准<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">console.time();启动定时器</span><br><span class="line">console.timeEnd();停止定时器，并进行输出</span><br><span class="line"></span><br><span class="line">#如下代码，执行</span><br><span class="line">var sum = 0;</span><br><span class="line">var arr = new Array(1000000);</span><br><span class="line">for (var i = 0; i &lt; arr.length; i++) &#123;</span><br><span class="line">    arr[i] = Math.random();</span><br><span class="line">&#125;</span><br><span class="line">console.time('for-loop-1');</span><br><span class="line">for (var i in arr) &#123;</span><br><span class="line">    sum += arr[i];</span><br><span class="line">&#125;</span><br><span class="line">console.timeEnd('for-loop-1');</span><br><span class="line">console.time('for-loop-2');</span><br><span class="line">for (var i = 0; i &lt; arr.length; i++) &#123;</span><br><span class="line">    sum += arr[i];</span><br><span class="line">&#125;</span><br><span class="line">console.timeEnd('for-loop-2');</span><br><span class="line"></span><br><span class="line">#输出如下</span><br><span class="line">for-loop-1: 396ms</span><br><span class="line">for-loop-2: 20ms</span><br></pre></td></tr></table></figure></p>
<p>　　堆栈踪迹：console.trace();通常情况下，错误或者bug可能位于从其他文件或模块中包含进来的代码里，堆栈跟踪让开发人员可以了解到脚本如何执行到某个点，并追踪问题发生的位置<br>　　Node.js调试器：在代码需要位置加入debugger，通过node debug xxxxx以调试方式启动。使用麻烦，不做讨论<br>　　Node Inspector：调试nodejs最有用的工具。启动Node Inspector的过程分为两部分。首先，使–debug或者–debug-brk标志启动应用程序，以便启动Javascript调试器。–debug-brk会在应用程序的第一行位置放射至一个端点<br>其次，另起一个Node Inspector的进程，即在另个终端中输入node-inspector。具体步骤如下：<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">#首先确保电脑上安装有webkit浏览器，如chrome,safari。</span><br><span class="line">#全局安装node inspector</span><br><span class="line">npm install -g node-inspector</span><br><span class="line">#新建app.js，输入如下内容</span><br><span class="line">var foo = function() &#123;</span><br><span class="line">    var a = 3,</span><br><span class="line">    b = 5;</span><br><span class="line">    var bar = function() &#123;</span><br><span class="line">        var b = 7,</span><br><span class="line">        c = 11;</span><br><span class="line">        a += b + c;</span><br><span class="line">    &#125;</span><br><span class="line">    bar();</span><br><span class="line">&#125;;</span><br><span class="line">foo();</span><br><span class="line">#在终端A中运行node --debug-brk app.js</span><br><span class="line">#在终端B中运行node-inspector（在app.js文件所在的位置）</span><br><span class="line">#打开浏览器访问http://127.0.0.1:8080/debug?port=5858，开始进行单步调试</span><br></pre></td></tr></table></figure></p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://nodeapi.ucdok.com/#/api/" target="_blank" rel="external">http://nodeapi.ucdok.com/#/api/</a><br><a href="http://nodeschool.io/" target="_blank" rel="external">http://nodeschool.io/</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/08/nodejs/1.NodeJS系列之概述/" data-id="cijzzpv6900481cfshpbzger4" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/nodejs/">nodejs</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/8.AOP系列之Javassist" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/01/java/8.AOP系列之Javassist/" class="article-date">
  <time datetime="2015-12-01T11:21:50.000Z" itemprop="datePublished">2015-12-01</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/01/java/8.AOP系列之Javassist/">AOP系列八之Javassist</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　如果我们实现了一个自定义类加载器，在类加载到JVM之前直接修改某些类的方法，并将切入逻辑织入到这个方法里，然后将修改后的字节码文件交给虚拟机运行，那岂不是更直接。<br><img src="/images/javassist1.jpg" alt="javassist1.jpg"><br>　　Javassist是一个编辑字节码的框架，可以让你很简单地操作字节码。它可以在运行期定义或修改Class。使用Javassist实现AOP的原理是在字节码加载前直接修改需要切入的方法。这比使用Cglib实现AOP更加高效，并且没太多限制，实现原理如下图：<br><img src="/images/javassist2.jpg" alt="javassist2.jpg"><br>　　我们使用系统类加载器启动我们自定义的类加载器，在这个类加载器里加一个类加载监听器，监听器发现目标类被加载时就织入切入逻辑，咱们再看看使用Javassist实现AOP的代码： </p>
<h2 id="u7CFB_u5217_u6587_u7AE0"><a href="#u7CFB_u5217_u6587_u7AE0" class="headerlink" title="系列文章"></a>系列文章</h2><p><a href="/../1.AOP系列之概述/">1. AOP系列之概述</a><br><a href="/../2.AOP系列之AspectJ/">2. AOP系列之AspectJ</a><br><a href="/../3.AOP系列之JDK Proxy/">3. AOP系列之JDK Proxy</a><br><a href="/../4.AOP系列之CGLIB/">4. AOP系列之CGLIB</a><br><a href="/../5.AOP系列之CGLIB源码学习/">5. AOP系列之CGLIB源码学习</a><br><a href="/../6.AOP系列之Spring AOP/">6. AOP系列之Spring AOP</a><br><a href="/../7.AOP系列之Spring AspectJ/">7. AOP系列之Spring AspectJ</a></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://www.iteye.com/topic/1116696" target="_blank" rel="external">http://www.iteye.com/topic/1116696</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/01/java/8.AOP系列之Javassist/" data-id="cijzzpvd300c11cfsiyj7d55p" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/aop/">aop</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/javassist/">javassist</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/7.AOP系列之Spring AspectJ" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/01/java/7.AOP系列之Spring AspectJ/" class="article-date">
  <time datetime="2015-12-01T10:21:36.000Z" itemprop="datePublished">2015-12-01</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/01/java/7.AOP系列之Spring AspectJ/">AOP系列七之Spring AspectJ</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><h2 id="u793A_u4F8B"><a href="#u793A_u4F8B" class="headerlink" title="示例"></a>示例</h2><p>　　在pom.xml中引入需要jar包<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">	&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">	&lt;artifactId&gt;spring-boot-starter-aop&lt;/artifactId&gt;</span><br><span class="line">	&lt;version&gt;$&#123;spring.boot.version&#125;&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure></p>
<p>　　新建HelloWorldAspectJ类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Aspect</span></span><br><span class="line"><span class="annotation">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldAspectJ</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Around</span>(<span class="string">"execution(* com.openim.spring.aop.IHelloWorld.*(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">around</span><span class="params">(ProceedingJoinPoint pjp)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        before();</span><br><span class="line">        Object result = pjp.proceed();</span><br><span class="line">        after();</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"AspectJ Before"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">after</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"AspectJ After"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　注意：类上面标注的 @Aspect 注解，这表明该类是一个 Aspect（其实就是 Advisor）。该类无需实现任何的接口，只需定义一个方法（方法叫什么名字都无所谓），只需在方法上标注 @Around 注解，在注解中使用了 AspectJ 切点表达式。方法的参数中包括一个 ProceedingJoinPoint 对象，它在 AOP 中称为 Joinpoint（连接点），可以通过该对象获取方法的任何信息，例如：方法名、参数等。下面重点来分析一下这个切点表达式：execution(<em> com.openim.spring.aop.IHelloWorld.</em>(..))<br>　　1. execution()：表示拦截方法，括号中可定义需要匹配的规则<br>　　2. 第一个*：表示方法的返回值是任意的<br>　　3. 第二个*：表示匹配该类中所有的方法<br>　　4. (..)：表示方法的参数是任意的。如果想匹配指定的方法，只需将第二个“*”改为指定的方法名称即可</p>
<h2 id="u81EA_u5B9A_u4E49_u6CE8_u89E3_u62E6_u622A"><a href="#u81EA_u5B9A_u4E49_u6CE8_u89E3_u62E6_u622A" class="headerlink" title="自定义注解拦截"></a>自定义注解拦截</h2><p>　　为了拦截指定的注解的方法，首先自定义一个注解<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Target</span>(ElementType.METHOD)</span><br><span class="line"><span class="annotation">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="keyword">public</span> <span class="annotation">@interface</span> Hello &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　修改HelloWorldAspectJ类，增加方法<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Around</span>(<span class="string">"@annotation(com.openim.spring.aop.Hello)"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">anno</span><span class="params">(ProceedingJoinPoint pjp)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"AspectJ Annotation Before"</span>);</span><br><span class="line">    Object result = pjp.proceed();</span><br><span class="line">    System.out.println(<span class="string">"AspectJ Annotation After"</span>);</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　在 <em>HelloWorldImpl</em> 类的testEarth方法上增加注解：@Hello，再修改 <em>SpringAopApplication</em> 类中的run方法如下。注意，此时@Hello必须在实现类上，而不能在接口IHelloWorld上<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(String... args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">       IHelloWorld greeting = applicationContext.getBean(IHelloWorld.class);</span><br><span class="line">       <span class="comment">//testEarth方法上存在注解</span></span><br><span class="line">       greeting.testEarth(<span class="string">"张三"</span>);</span><br><span class="line">       System.out.println();</span><br><span class="line">       greeting.testMars(<span class="string">"李四"</span>);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>　　运行，结果如下<br>　　AspectJ Annotation Before<br>　　AspectJ Before<br>　　欢迎张三来到地球<br>　　AspectJ After<br>　　AspectJ Annotation After<br>　　<br>　　AspectJ Before<br>　　欢迎李四来到火星<br>　　AspectJ After</p>
<p>　　除了 @Around 注解外，其实还有几个相关的注解，稍微归纳一下吧：<br>　　1. @Before：前置增强<br>　　2. @After：后置增强<br>　　3. @Around：环绕增强<br>　　4. @AfterThrowing：抛出增强<br>　　5. @DeclareParents：引入增强<br>　　此外还有一个 @AfterReturning（返回后增强），也可理解为 Finally 增强，相当于 finally 语句，它是在方法结束后执行的，也就说说，它比 @After 还要晚一些。最后一个 @DeclareParents 竟然就是引入增强！为什么不叫做 @Introduction 呢？我也不知道为什么，但它干的活就是引入增强。</p>
<h2 id="u5F15_u5165_u589E_u5F3A"><a href="#u5F15_u5165_u589E_u5F3A" class="headerlink" title="引入增强"></a>引入增强</h2><p>　　首先，定义接口IHelloPK<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IHelloPK</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">helloPk</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　接着，定义该接口的实现类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloPKImpl</span> <span class="keyword">implements</span> <span class="title">IHelloPK</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">helloPk</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"helloPk! "</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　然后，修改HelloWorldAspectJ，增加如下内容<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@DeclareParents</span>(value = <span class="string">"com.openim.spring.aop.HelloWorldImpl"</span>, defaultImpl = HelloPKImpl.class)</span><br><span class="line"><span class="keyword">private</span> IHelloPK helloPK;</span><br></pre></td></tr></table></figure></p>
<p>　　其中注解DeclareParents的value代表目标类，defaultImpl表示引入接口的默认实现，运行时IHelloPK会自动增强到HelloWorldImpl中。修改 <em>SpringAopApplication</em> 类中的run方法如下<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(String... args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    IHelloWorld greeting = applicationContext.getBean(IHelloWorld.class);</span><br><span class="line">    greeting.testMars(<span class="string">"李四"</span>);</span><br><span class="line"></span><br><span class="line">    IHelloPK helloPK = (IHelloPK)greeting;</span><br><span class="line">    helloPK.helloPk();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　运行后，输出如下内容：<br>　　AspectJ Before<br>　　欢迎李四来到火星<br>　　AspectJ After<br>　　helloPk!</p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　下面附上网上的一张图<br><img src="/images/aop-introduce.png" alt="aop-introduce"><br>　　再来一张表格，总结一下各类增强类型所对应的解决方案，也是从网上找的：</p>
<table>
<thead>
<tr>
<th>增强类型</th>
<th style="text-align:left">基于 AOP 接口</th>
<th style="text-align:left">基于 @Aspect</th>
<th style="text-align:left">基于 &lt;aop:config&gt;</th>
</tr>
</thead>
<tbody>
<tr>
<td>Before Advice（前置增强）</td>
<td style="text-align:left">MethodBeforeAdvice</td>
<td style="text-align:left">@Before</td>
<td style="text-align:left">&lt;aop:before&gt;</td>
</tr>
<tr>
<td>AfterAdvice（后置增强）</td>
<td style="text-align:left">AfterReturningAdvice</td>
<td style="text-align:left">@After</td>
<td style="text-align:left">&lt;aop:after&gt;</td>
</tr>
<tr>
<td>AroundAdvice（环绕增强）</td>
<td style="text-align:left">MethodInterceptor</td>
<td style="text-align:left">@Around</td>
<td style="text-align:left">&lt;aop:around&gt;</td>
</tr>
<tr>
<td>ThrowsAdvice（抛出增强）</td>
<td style="text-align:left">ThrowsAdvice</td>
<td style="text-align:left">@AfterThrowing</td>
<td style="text-align:left">&lt;aop:after-throwing&gt;</td>
</tr>
<tr>
<td>IntroductionAdvice（引入增强）</td>
<td style="text-align:left">DelegatingIntroductionInterceptor</td>
<td style="text-align:left">@DeclareParents</td>
<td style="text-align:left">&lt;aop:declare-parents&gt;</td>
</tr>
</tbody>
</table>
<p>　　最后附上一张图<br><img src="/images/spring-aop-uml.png" alt="spring-aop-uml"></p>
<p>　　以上代码下载地址：<a href="/code/openim-aop3.zip">openim-aop3.zip</a></p>
<h2 id="u7CFB_u5217_u6587_u7AE0"><a href="#u7CFB_u5217_u6587_u7AE0" class="headerlink" title="系列文章"></a>系列文章</h2><p><a href="/../1.AOP系列之概述/">1. AOP系列之概述</a><br><a href="/../2.AOP系列之AspectJ/">2. AOP系列之AspectJ</a><br><a href="/../3.AOP系列之JDK Proxy/">3. AOP系列之JDK Proxy</a><br><a href="/../4.AOP系列之CGLIB/">4. AOP系列之CGLIB</a><br><a href="/../5.AOP系列之CGLIB源码学习/">5. AOP系列之CGLIB源码学习</a><br><a href="/../6.AOP系列之Spring AOP/">6. AOP系列之Spring AOP</a><br><a href="/../7.AOP系列之Spring AspectJ/">7. AOP系列之Spring AspectJ</a></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://my.oschina.net/huangyong/blog/161402" target="_blank" rel="external">http://my.oschina.net/huangyong/blog/161402</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/01/java/7.AOP系列之Spring AspectJ/" data-id="cijzzpvd800c81cfs6eh1cars" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/aop/">aop</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/aspectj/">aspectj</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/spring/">spring</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/6.AOP系列之Spring AOP" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/01/java/6.AOP系列之Spring AOP/" class="article-date">
  <time datetime="2015-12-01T09:21:36.000Z" itemprop="datePublished">2015-12-01</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/01/java/6.AOP系列之Spring AOP/">AOP系列六之Spring AOP</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><h2 id="u793A_u4F8B"><a href="#u793A_u4F8B" class="headerlink" title="示例"></a>示例</h2><p>　　首先定义一个接口IHelloWorld和实现类HelloWorldImpl<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.openim.spring.aop;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IHelloWorld</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">hello</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.openim.spring.aop;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"><span class="annotation">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldImpl</span> <span class="keyword">implements</span> <span class="title">IHelloWorld</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"HelloWorld"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>　　接着定义一个前置增强类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.openim.spring.aop;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.aop.MethodBeforeAdvice;</span><br><span class="line"><span class="keyword">import</span> org.springframework.aop.framework.ProxyFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span><br><span class="line"> * MethodBeforeAdvice接口由spring提供</span><br><span class="line"> */</span></span><br><span class="line"><span class="annotation">@Component</span>(<span class="string">"beforeAdvice"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldBeforeAdvice</span> <span class="keyword">implements</span> <span class="title">MethodBeforeAdvice</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">(Method method, Object[] args, Object target)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Before"</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　再定义一个后置增强类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.openim.spring.aop;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.aop.AfterReturningAdvice;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span><br><span class="line"> * AfterReturningAdvice接口由spring提供</span><br><span class="line"> */</span></span><br><span class="line"><span class="annotation">@Component</span>(<span class="string">"afterAdvice"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldAfterAdvice</span> <span class="keyword">implements</span> <span class="title">AfterReturningAdvice</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterReturning</span><span class="params">(Object returnValue, Method method, Object[] args, Object target)</span> </span><br><span class="line">	<span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"After"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　最后定义一个环绕类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.openim.spring.aop;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.aopalliance.intercept.MethodInterceptor;</span><br><span class="line"><span class="keyword">import</span> org.aopalliance.intercept.MethodInvocation;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span><br><span class="line"> * MethodInterceptor接口由aop联盟提供</span><br><span class="line"> */</span></span><br><span class="line"><span class="annotation">@Component</span>(<span class="string">"aroundAdvice"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldAround</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span></span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(MethodInvocation invocation)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"around before"</span>);</span><br><span class="line">        Object result = invocation.proceed();</span><br><span class="line">        System.out.println(<span class="string">"around after"</span>);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　定义一个测试类并运行<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ProxyFactory proxyFactory = <span class="keyword">new</span> ProxyFactory();     <span class="comment">// 创建代理工厂</span></span><br><span class="line">        proxyFactory.setTarget(<span class="keyword">new</span> HelloWorldImpl());         <span class="comment">// 射入目标类对象</span></span><br><span class="line">        proxyFactory.addAdvice(<span class="keyword">new</span> HelloWorldBeforeAdvice()); <span class="comment">// 添加前置增强</span></span><br><span class="line">        proxyFactory.addAdvice(<span class="keyword">new</span> HelloWorldAfterAdvice());  <span class="comment">// 添加后置增强</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//spring boot默认采用CGLib的方式</span></span><br><span class="line">        IHelloWorld greeting = (IHelloWorld) proxyFactory.getProxy(); <span class="comment">// 从代理工厂中获取代理</span></span><br><span class="line">        greeting.hello();                              <span class="comment">// 调用代理的方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>输出如下:<br>Before<br>HelloWorld<br>After</p>
<p>　　或者采用spring boot测试类，此时需要先定义个Configuration类，再实现启动类SpringAopApplication<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AopConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span>(name = <span class="string">"helloWorldProxy"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ProxyFactoryBean <span class="title">proxyFactoryBean</span><span class="params">(IHelloWorld helloWorld)</span></span>&#123;</span><br><span class="line">        ProxyFactoryBean proxyFactoryBean = <span class="keyword">new</span> ProxyFactoryBean();</span><br><span class="line">        <span class="comment">//需要代理的接口</span></span><br><span class="line">        proxyFactoryBean.setInterfaces(IHelloWorld.class);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//接口实现类</span></span><br><span class="line">        proxyFactoryBean.setTarget(helloWorld);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//拦截器名称（也就是增强类名称，Spring Bean 的 id）</span></span><br><span class="line">        proxyFactoryBean.setInterceptorNames(<span class="string">"beforeAdvice"</span>, <span class="string">"afterAdvice"</span>, <span class="string">"aroundAdvice"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> proxyFactoryBean;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.openim.spring;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.openim.spring.aop.HelloWorldImpl;</span><br><span class="line"><span class="keyword">import</span> com.openim.spring.aop.IHelloWorld;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.CommandLineRunner;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.SpringApplication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.ApplicationContext;</span><br><span class="line"></span><br><span class="line"><span class="annotation">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringAopApplication</span> <span class="keyword">implements</span> <span class="title">CommandLineRunner</span></span>&#123;</span><br><span class="line">    <span class="annotation">@Autowired</span></span><br><span class="line">    ApplicationContext applicationContext;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication springApplication = <span class="keyword">new</span> SpringApplication(SpringAopApplication.class);</span><br><span class="line">        springApplication.run(args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(String... args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//输出了增强方法</span></span><br><span class="line">        IHelloWorld greeting = (IHelloWorld) applicationContext.getBean(<span class="string">"helloWorldProxy"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//未输出advice增强方法，只打印了System.out.println("HelloWorld");</span></span><br><span class="line">        <span class="comment">//IHelloWorld greeting = (IHelloWorld) applicationContext.getBean(HelloWorldImpl.class);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//错误NoUniqueBeanDefinitionException，提示找到两个bean helloWorldImpl,helloWorldProxy</span></span><br><span class="line">        <span class="comment">//IHelloWorld greeting = (IHelloWorld) applicationContext.getBean(IHelloWorld.class);</span></span><br><span class="line"></span><br><span class="line">        greeting.hello();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出如下:<br>Before<br>around before<br>HelloWorld<br>around after<br>After</p>
<p>　　此时需要引入依赖<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="title">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="title">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">version</span>&gt;</span>1.2.4.RELEASE<span class="tag">&lt;/<span class="title">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>　　如果程序报错，抛出异常了，一般的做法是打印到控制台或日志文件中，这样很多地方都得去处理，有没有一个一劳永逸的方法呢？那就是Throws Advice（抛出增强）。修改<em>HelloWorldImpl</em>如下，抛出一个错误。注意，如果在方法中用了try catch 代码，则必须要在<em>catch</em>代码块中<em>throw</em>，否则错误不会被捕捉到。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldImpl</span> <span class="keyword">implements</span> <span class="title">IHelloWorld</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//System.out.println("HelloWorld");</span></span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"HelloWorld"</span>);</span><br><span class="line">            <span class="comment">// 故意抛出一个异常，看看异常信息能否被拦截到</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Error"</span>); </span><br><span class="line">        &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">            System.out.println(e.toString());</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　再定义一个错误增强<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Component</span>(<span class="string">"throwsAdvice"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldThrowsAdvice</span> <span class="keyword">implements</span> <span class="title">ThrowsAdvice</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterThrowing</span><span class="params">(Method method, Object[] args, Object target, Exception e)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"---------- Throw Exception ----------"</span>);</span><br><span class="line">        System.out.println(<span class="string">"Target Class: "</span> + target.getClass().getName());</span><br><span class="line">        System.out.println(<span class="string">"Method Name: "</span> + method.getName());</span><br><span class="line">        System.out.println(<span class="string">"Exception Message: "</span> + e.getMessage());</span><br><span class="line">        System.out.println(<span class="string">"-------------------------------------"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>最后修改代码<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">proxyFactoryBean.setInterceptorNames(<span class="string">"beforeAdvice"</span>, <span class="string">"afterAdvice"</span>, <span class="string">"aroundAdvice"</span>);</span><br></pre></td></tr></table></figure></p>
<p>为<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">proxyFactoryBean.setInterceptorNames(<span class="string">"beforeAdvice"</span>, <span class="string">"afterAdvice"</span>, <span class="string">"aroundAdvice"</span>, <span class="string">"throwsAdvice"</span>);</span><br></pre></td></tr></table></figure></p>
<p>　　打印信息如下<br>Before<br>around before<br>HelloWorld<br>java.lang.RuntimeException: Error<br>———- Throw Exception ———-<br>Target Class: com.openim.spring.aop.HelloWorldImpl<br>Method Name: hello</p>
<h2 id="Exception_Message_3A_java-lang-RuntimeException_3A_Error"><a href="#Exception_Message_3A_java-lang-RuntimeException_3A_Error" class="headerlink" title="Exception Message: java.lang.RuntimeException: Error"></a>Exception Message: java.lang.RuntimeException: Error</h2><p>2015-12-05 16:57:33.099  INFO 8872 — [           main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: ……..<br>2015-12-05 16:57:33.101  INFO 8872 — [           main] utoConfigurationReportLoggingInitializer : </p>
<p>Error starting ApplicationContext. To display the auto-configuration report enable debug logging (start with –debug)<br>…….</p>
<p>　　可以看到，最后程序运行失败。如果将类<em>HelloWorldThrowsAdvice</em>中的方法用try cathch包裹，仍然失败，说明<strong>ThrowsAdvice只能捕获到异常，但是无法处理异常</strong>。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>&#123;</span><br><span class="line">	System.out.println(<span class="string">"---------- Throw Exception ----------"</span>);</span><br><span class="line">	System.out.println(<span class="string">"Target Class: "</span> + target.getClass().getName());</span><br><span class="line">	System.out.println(<span class="string">"Method Name: "</span> + method.getName());</span><br><span class="line">	System.out.println(<span class="string">"Exception Message: "</span> + e.getMessage());</span><br><span class="line">	System.out.println(<span class="string">"-------------------------------------"</span>);</span><br><span class="line">&#125;<span class="keyword">catch</span> (Exception ex)&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="u5F15_u5165_u589E_u5F3A"><a href="#u5F15_u5165_u589E_u5F3A" class="headerlink" title="引入增强"></a>引入增强</h2><p>　　以上提到的都是对方法的增强，那能否对类进行增强呢？用 AOP 的话来讲，对方法的增强叫做 Weaving（织入），而对类的增强叫做 Introduction（引入）。而Introduction Advice（引入增强）就是对类的功能增强（增加方法），它也是 Spring AOP 提供的最后一种增强。简单点说，即在不修改原有类的情况下，对原有类增加新的方法。下面演示了给类 <em>HelloWorldImpl</em> 增加新的方法<em>helloPk()</em>。首先定义一个新接口 <em>IHelloPK</em>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.openim.spring.aop;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IHelloPK</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">helloPk</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　定义一个新的实现类 <em>HelloPKAdvice</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloPKAdvice</span> <span class="keyword">extends</span> <span class="title">DelegatingIntroductionInterceptor</span> <span class="keyword">implements</span> <span class="title">IHelloPK</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(MethodInvocation invocation)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">super</span>.invoke(invocation);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">helloPk</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"helloPk! "</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　以上定义了一个引入增强类，扩展了<em>org.springframework.aop.support.DelegatingIntroductionInterceptor</em>类。在类中首先覆盖了父类的<em>invoke()</em> 方法，然后实现了<em>IHelloPK</em>接口的方法。我就是想用这个增强类去丰富<em>HelloWorldImpl</em>类的功能，那么这个<em>HelloWorldImpl</em>类无需直接实现<em>IHelloPK</em>接口，就可以在程序运行的时候调用 IHelloPK 接口的方法了！该怎么做呢？其实只需要修改类 <em>AopConfiguration</em> 的实现即可。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AopConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span>(name = <span class="string">"helloWorldProxy"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ProxyFactoryBean <span class="title">proxyFactoryBean</span><span class="params">(IHelloWorld helloWorld)</span></span>&#123;</span><br><span class="line">        ProxyFactoryBean proxyFactoryBean = <span class="keyword">new</span> ProxyFactoryBean();</span><br><span class="line">        <span class="comment">//需要代理的接口，增加了HelloPK.class</span></span><br><span class="line">        proxyFactoryBean.setInterfaces(IHelloWorld.class, IHelloPK.class);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//接口实现类</span></span><br><span class="line">        proxyFactoryBean.setTarget(helloWorld);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//拦截器名称，增加了helloPKAdvice</span></span><br><span class="line">        proxyFactoryBean.setInterceptorNames(<span class="string">"beforeAdvice"</span>,</span><br><span class="line">                <span class="string">"afterAdvice"</span>,</span><br><span class="line">                <span class="string">"helloPKAdvice"</span>);</span><br><span class="line">        proxyFactoryBean.setProxyTargetClass(<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span> proxyFactoryBean;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　最后修改测试代码如下<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringAopApplication</span> <span class="keyword">implements</span> <span class="title">CommandLineRunner</span></span>&#123;</span><br><span class="line">    <span class="annotation">@Autowired</span></span><br><span class="line">    ApplicationContext applicationContext;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication springApplication = <span class="keyword">new</span> SpringApplication(SpringAopApplication.class);</span><br><span class="line">        springApplication.run(args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(String... args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        IHelloWorld greeting = (IHelloWorld) applicationContext.getBean(<span class="string">"helloWorldProxy"</span>);</span><br><span class="line">        greeting.hello();</span><br><span class="line">        System.out.println(<span class="string">""</span>);</span><br><span class="line">        <span class="comment">//强转为IHelloPK</span></span><br><span class="line">        IHelloPK helloPK = (IHelloPK) greeting;</span><br><span class="line">        helloPK.helloPk();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>运行程序，输出：<br>Before<br>HelloWorld<br>java.lang.RuntimeException: Error<br>After</p>
<p>Before<br>helloPk!<br>After</p>
<p>以上代码下载地址：<a href="/code/openim-aop1.zip">openim-aop1.zip</a></p>
<h2 id="u5207_u9762"><a href="#u5207_u9762" class="headerlink" title="切面"></a>切面</h2><p>　　根据上面的学习，我们对 <em>HelloWorldImpl</em> 类的所有方法都进行了增强，可以理解为此时的AOP框架为：该AOP框架为一个拦截器框架，但这个拦截器似乎非常武断。比如说，如果它拦截了一个类，那么它就拦截了这个类中所有的方法。类似地，当我们在使用动态代理的时候，其实也遇到了这个问题。需要在代码中<em>对所拦截的方法名加以判断，才能过滤出我们需要拦截的方法</em>，想想这种做法确实不太优雅。在大量的真实项目中，似乎我们只需要拦截特定的方法就行了，没必要拦截所有的方法。于是，Rod Johnson（老罗）同志借助了 AOP 的一个很重要的工具，Advisor（切面），来解决这个问题。它也是 AOP 中的核心！是我们关注的重点！<br>　　也就是说，我们可以通过切面，将增强类与拦截匹配条件组合在一起，然后将这个切面配置到 ProxyFactory 中，从而生成代理。这里提到这个“拦截匹配条件”在 AOP 中就叫做Pointcut（切点），其实说白了就是一个基于表达式的拦截条件罢了。<br>　　首先给接口IHelloWorld和实现类HelloWorldImpl增加两个以test开头的方法<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloWorldImpl</span> <span class="keyword">implements</span> <span class="title">IHelloWorld</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"HelloWorld"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testEarth</span><span class="params">(String who)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"欢迎"</span> + who + <span class="string">"来到地球"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testMars</span><span class="params">(String who)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"欢迎"</span> + who + <span class="string">"来到火星"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>修改<em>AopConfiguration</em>类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AopConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span>(name = <span class="string">"helloWorldProxy"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ProxyFactoryBean <span class="title">proxyFactoryBean</span><span class="params">(IHelloWorld helloWorld)</span></span>&#123;</span><br><span class="line">        ProxyFactoryBean proxyFactoryBean = <span class="keyword">new</span> ProxyFactoryBean();</span><br><span class="line">        <span class="comment">//需要代理的接口</span></span><br><span class="line">        proxyFactoryBean.setInterfaces(IHelloWorld.class);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//接口实现类</span></span><br><span class="line">        proxyFactoryBean.setTarget(helloWorld);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//拦截器名</span></span><br><span class="line">        proxyFactoryBean.setInterceptorNames(<span class="string">"helloWorldBeforeAdvisor"</span>, <span class="string">"helloWorldAfterAdvisor"</span>);</span><br><span class="line">        proxyFactoryBean.setProxyTargetClass(<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span> proxyFactoryBean;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RegexpMethodPointcutAdvisor <span class="title">helloWorldBeforeAdvisor</span><span class="params">(HelloWorldBeforeAdvice beforeAdvice)</span></span>&#123;</span><br><span class="line">        RegexpMethodPointcutAdvisor advisor = <span class="keyword">new</span> RegexpMethodPointcutAdvisor();</span><br><span class="line">        advisor.setAdvice(beforeAdvice);</span><br><span class="line">        <span class="comment">//不能是接口，必须是实现类</span></span><br><span class="line">        advisor.setPattern(<span class="string">"com.openim.spring.aop.HelloWorldImpl.test.*"</span>);</span><br><span class="line">        <span class="keyword">return</span> advisor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RegexpMethodPointcutAdvisor <span class="title">helloWorldAfterAdvisor</span><span class="params">(HelloWorldAfterAdvice afterAdvice)</span></span>&#123;</span><br><span class="line">        RegexpMethodPointcutAdvisor advisor = <span class="keyword">new</span> RegexpMethodPointcutAdvisor();</span><br><span class="line">        advisor.setAdvice(afterAdvice);</span><br><span class="line">        <span class="comment">//不能是接口，必须是实现类</span></span><br><span class="line">        advisor.setPattern(<span class="string">"com.openim.spring.aop.HelloWorldImpl.test.*"</span>);</span><br><span class="line">        <span class="keyword">return</span> advisor;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　修改测试代码<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringAopApplication</span> <span class="keyword">implements</span> <span class="title">CommandLineRunner</span></span>&#123;</span><br><span class="line">    <span class="annotation">@Autowired</span></span><br><span class="line">    ApplicationContext applicationContext;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication springApplication = <span class="keyword">new</span> SpringApplication(SpringAopApplication.class);</span><br><span class="line">        springApplication.run(args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(String... args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        IHelloWorld greeting = (IHelloWorld) applicationContext.getBean(<span class="string">"helloWorldProxy"</span>);</span><br><span class="line">        greeting.testEarth(<span class="string">"张三"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　输出如下<br>Before<br>欢迎张三来到地球<br>After</p>
<p>　　此时我们可以发现，proxyFactoryBean.setInterceptorNames中，此时传入的不再是advice，而是advisor。即此时传入的不再是增强，而是一个切面。此外，该切面还定义了一个切点（正则表达式），其目的是为了只将满足切点匹配条件的方法进行拦截。需要强调的是，这里的切点表达式是基于正则表达式的。示例中的 <em>com.openim.spring.aop.HelloWorldImpl.test.</em> 表达式后面的 .* 表示匹配所有字符，翻译过来就是匹配 <em>com.openim.spring.aop.HelloWorldImpl</em> 类中以 <em>test</em> 开头的方法。除了 <em>RegexpMethodPointcutAdvisor</em> 以外，在 Spring AOP 中还提供了几个切面类，比如：<br>　　1. DefaultPointcutAdvisor：默认切面（可扩展它来自定义切面）<br>　　2. NameMatchMethodPointcutAdvisor：根据方法名称进行匹配的切面<br>　　3. StaticMethodMatcherPointcutAdvisor：用于匹配静态方法的切面<br>　　总的来说，让用户去配置一个或少数几个代理，似乎还可以接受，但随着项目的扩大，代理配置就会越来越多，配置的重复劳动就多了，麻烦不说，还很容易出错。能否让 Spring 框架为我们自动生成代理呢？</p>
<h2 id="u81EA_u52A8_u4EE3_u7406_uFF08_u626B_u63CF_Bean__u540D_u79F0_uFF09"><a href="#u81EA_u52A8_u4EE3_u7406_uFF08_u626B_u63CF_Bean__u540D_u79F0_uFF09" class="headerlink" title="自动代理（扫描 Bean 名称）"></a>自动代理（扫描 Bean 名称）</h2><p>　　Spring AOP 提供了一个可根据 Bean 名称来自动生成代理的工具，它就是 <em>BeanNameAutoProxyCreator</em>。在下面的 <em>helloWorldProxyCreator()</em> 使用中，BeanNameAutoProxyCreator 只为后缀为“Impl”的 Bean 生成代理。需要注意的是，这个地方我们不能定义代理接口，也就是 interfaces 属性，因为我们根本就不知道这些 Bean 到底实现了多少接口。此时不能代理接口，而只能代理类。所以这里提供了一个新的配置项，它就是 optimize。若为 true 时，则可对代理生成策略进行优化（默认是 false 的）。也就是说，如果该类有接口，就代理接口（使用 JDK 动态代理）；如果没有接口，就代理类（使用 CGLib 动态代理）。而并非像之前使用的 proxyTargetClass 属性那样，强制代理类，而不考虑代理接口的方式。可见 Spring AOP 确实为我们提供了很多很好地服务！<br>　　既然 CGLib 可以代理任何的类了，那为什么还要用 JDK 的动态代理呢？肯定您会这样问。根据多年来实际项目经验得知：CGLib 创建代理的速度比较慢，但创建代理后运行的速度却非常快，而 JDK 动态代理正好相反。如果在运行的时候不断地用 CGLib 去创建代理，系统的性能会大打折扣，所以建议一般在系统初始化的时候用 CGLib 去创建代理，并放入 Spring 的 ApplicationContext 中以备后用。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AopConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*@Bean(name = "helloWorldProxy")</span><br><span class="line">    public ProxyFactoryBean proxyFactoryBean(IHelloWorld helloWorld)&#123;</span><br><span class="line">        ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();</span><br><span class="line">        //需要代理的接口</span><br><span class="line">        proxyFactoryBean.setInterfaces(IHelloWorld.class);</span><br><span class="line"></span><br><span class="line">        //接口实现类</span><br><span class="line">        proxyFactoryBean.setTarget(helloWorld);</span><br><span class="line"></span><br><span class="line">        //拦截器名</span><br><span class="line">        proxyFactoryBean.setInterceptorNames("helloWorldBeforeAdvisor", "helloWorldAfterAdvisor");</span><br><span class="line">        proxyFactoryBean.setProxyTargetClass(true);</span><br><span class="line">        return proxyFactoryBean;</span><br><span class="line">    &#125;*/</span></span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RegexpMethodPointcutAdvisor <span class="title">helloWorldBeforeAdvisor</span><span class="params">(HelloWorldBeforeAdvice beforeAdvice)</span></span>&#123;</span><br><span class="line">        RegexpMethodPointcutAdvisor advisor = <span class="keyword">new</span> RegexpMethodPointcutAdvisor();</span><br><span class="line">        advisor.setAdvice(beforeAdvice);</span><br><span class="line">        <span class="comment">//不能是接口，必须是实现类</span></span><br><span class="line">        advisor.setPattern(<span class="string">"com.openim.spring.aop.HelloWorldImpl.test.*"</span>);</span><br><span class="line">        <span class="keyword">return</span> advisor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RegexpMethodPointcutAdvisor <span class="title">helloWorldAfterAdvisor</span><span class="params">(HelloWorldAfterAdvice afterAdvice)</span></span>&#123;</span><br><span class="line">        RegexpMethodPointcutAdvisor advisor = <span class="keyword">new</span> RegexpMethodPointcutAdvisor();</span><br><span class="line">        advisor.setAdvice(afterAdvice);</span><br><span class="line">        <span class="comment">//不能是接口，必须是实现类</span></span><br><span class="line">        advisor.setPattern(<span class="string">"com.openim.spring.aop.HelloWorldImpl.test.*"</span>);</span><br><span class="line">        <span class="keyword">return</span> advisor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> BeanNameAutoProxyCreator <span class="title">helloWorldProxyCreator</span><span class="params">()</span></span>&#123;</span><br><span class="line">        BeanNameAutoProxyCreator creator = <span class="keyword">new</span> BeanNameAutoProxyCreator();</span><br><span class="line">        creator.setBeanNames(<span class="string">"*Impl"</span>);</span><br><span class="line">        creator.setInterceptorNames(<span class="string">"helloWorldBeforeAdvisor"</span>, <span class="string">"helloWorldAfterAdvisor"</span>);</span><br><span class="line">        creator.setOptimize(<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span> creator;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　以上这个例子只能匹配目标类，而不能进一步匹配其中指定的方法，要匹配方法，就要考虑使用切面与切点了。Spring AOP 基于切面也提供了一个自动代理生成器：DefaultAdvisorAutoProxyCreator。</p>
<h2 id="u81EA_u52A8_u4EE3_u7406_uFF08_u626B_u63CF_u5207_u9762_u914D_u7F6E_uFF09"><a href="#u81EA_u52A8_u4EE3_u7406_uFF08_u626B_u63CF_u5207_u9762_u914D_u7F6E_uFF09" class="headerlink" title="自动代理（扫描切面配置）"></a>自动代理（扫描切面配置）</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AopConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RegexpMethodPointcutAdvisor <span class="title">helloWorldBeforeAdvisor</span><span class="params">(HelloWorldBeforeAdvice beforeAdvice)</span></span>&#123;</span><br><span class="line">        RegexpMethodPointcutAdvisor advisor = <span class="keyword">new</span> RegexpMethodPointcutAdvisor();</span><br><span class="line">        advisor.setAdvice(beforeAdvice);</span><br><span class="line">        <span class="comment">//不能是接口，必须是实现类</span></span><br><span class="line">        advisor.setPattern(<span class="string">"com.openim.spring.aop.HelloWorldImpl.test.*"</span>);</span><br><span class="line">        <span class="keyword">return</span> advisor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RegexpMethodPointcutAdvisor <span class="title">helloWorldAfterAdvisor</span><span class="params">(HelloWorldAfterAdvice afterAdvice)</span></span>&#123;</span><br><span class="line">        RegexpMethodPointcutAdvisor advisor = <span class="keyword">new</span> RegexpMethodPointcutAdvisor();</span><br><span class="line">        advisor.setAdvice(afterAdvice);</span><br><span class="line">        <span class="comment">//不能是接口，必须是实现类</span></span><br><span class="line">        advisor.setPattern(<span class="string">"com.openim.spring.aop.HelloWorldImpl.test.*"</span>);</span><br><span class="line">        <span class="keyword">return</span> advisor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DefaultAdvisorAutoProxyCreator <span class="title">defaultAdvisorAutoProxyCreator</span><span class="params">()</span></span>&#123;</span><br><span class="line">        DefaultAdvisorAutoProxyCreator creator = <span class="keyword">new</span> DefaultAdvisorAutoProxyCreator();</span><br><span class="line">        creator.setOptimize(<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span> creator;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="u601D_u8003"><a href="#u601D_u8003" class="headerlink" title="思考"></a>思考</h2><p>　　在 Spring 配置文件中，仍然会存在大量的切面配置。然而在有很多情况下 Spring AOP 所提供的切面类真的不太够用了，比如：想拦截指定注解的方法，我们就必须扩展 DefaultPointcutAdvisor 类，自定义一个切面类，然后在 Spring 配置文件中进行切面配置。不做不知道，做了您就知道相当麻烦了。<br>　　老罗的解决方案似乎已经掉进了切面类的深渊，这还真是所谓的“面向切面编程”了，最重要的是切面，最麻烦的也是切面。<br>　　必须要把切面配置给简化掉，Spring 才能有所突破！<br>　　神一样的老罗总算认识到了这一点，接受了网友们的建议，集成了 AspectJ，同时也保留了以上提到的切面与代理配置方式（为了兼容老的项目，更为了维护自己的面子）。将 Spring 与 AspectJ 集成与直接使用 AspectJ 是不同的，我们不需要定义 AspectJ 类（它是扩展了 Java 语法的一种新的语言，还需要特定的编译器），只需要使用 AspectJ 切点表达式即可（它是比正则表达式更加友好的表现形式）。<br>以上代码下载地址：<a href="/code/openim-aop2.zip">openim-aop2.zip</a></p>
<h2 id="u7CFB_u5217_u6587_u7AE0"><a href="#u7CFB_u5217_u6587_u7AE0" class="headerlink" title="系列文章"></a>系列文章</h2><p><a href="/../1.AOP系列之概述/">1. AOP系列之概述</a><br><a href="/../2.AOP系列之AspectJ/">2. AOP系列之AspectJ</a><br><a href="/../3.AOP系列之JDK Proxy/">3. AOP系列之JDK Proxy</a><br><a href="/../4.AOP系列之CGLIB/">4. AOP系列之CGLIB</a><br><a href="/../5.AOP系列之CGLIB源码学习/">5. AOP系列之CGLIB源码学习</a><br><a href="/../6.AOP系列之Spring AOP/">6. AOP系列之Spring AOP</a><br><a href="/../7.AOP系列之Spring AspectJ/">7. AOP系列之Spring AspectJ</a></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://my.oschina.net/huangyong/blog/161338" target="_blank" rel="external">http://my.oschina.net/huangyong/blog/161338</a><br><a href="http://www.iteye.com/topic/801577" target="_blank" rel="external">http://www.iteye.com/topic/801577</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/01/java/6.AOP系列之Spring AOP/" data-id="cijzzpvde00cf1cfs6zaclt3u" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/aop/">aop</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/aspectj/">aspectj</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/spring/">spring</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/5.AOP系列之CGLIB源码学习" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/01/java/5.AOP系列之CGLIB源码学习/" class="article-date">
  <time datetime="2015-12-01T08:21:36.000Z" itemprop="datePublished">2015-12-01</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/01/java/5.AOP系列之CGLIB源码学习/">AOP系列五之CGLIB源码学习</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　</p>
<h2 id="u7CFB_u5217_u6587_u7AE0"><a href="#u7CFB_u5217_u6587_u7AE0" class="headerlink" title="系列文章"></a>系列文章</h2><p><a href="/../1.AOP系列之概述/">1. AOP系列之概述</a><br><a href="/../2.AOP系列之AspectJ/">2. AOP系列之AspectJ</a><br><a href="/../3.AOP系列之JDK Proxy/">3. AOP系列之JDK Proxy</a><br><a href="/../4.AOP系列之CGLIB/">4. AOP系列之CGLIB</a><br><a href="/../5.AOP系列之CGLIB源码学习/">5. AOP系列之CGLIB源码学习</a><br><a href="/../6.AOP系列之Spring AOP/">6. AOP系列之Spring AOP</a><br><a href="/../7.AOP系列之Spring AspectJ/">7. AOP系列之Spring AspectJ</a></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://agapple.iteye.com/blog/799827" target="_blank" rel="external">http://agapple.iteye.com/blog/799827</a><br><a href="http://www.iteye.com/topic/801577" target="_blank" rel="external">http://www.iteye.com/topic/801577</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/01/java/5.AOP系列之CGLIB源码学习/" data-id="cijzzpvdi00cl1cfsv7dpzwgq" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/aop/">aop</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/gclib/">gclib</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-rpc/16.RPC系列之基于Netty、ZK的实现原型" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/01/rpc/16.RPC系列之基于Netty、ZK的实现原型/" class="article-date">
  <time datetime="2015-12-01T08:00:00.000Z" itemprop="datePublished">2015-12-01</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/rpc/">rpc</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/01/rpc/16.RPC系列之基于Netty、ZK的实现原型/">RPC系列十六之基于Netty、ZK的实现原型</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　在rpc系列第一篇中，我们采用jdk proxy和socket实现了一个最简单的rpc调动过程。在本篇文章中，我们将socket替换成成熟了netty框架，并引入zookeeper实现服务注册与发现机制，序列化机制采用protostuff。注意：该文章为转载，忘了原链接了，但是在文章最后会加入简单的分析。</p>
<h2 id="u670D_u52A1_u6CE8_u518C"><a href="#u670D_u52A1_u6CE8_u518C" class="headerlink" title="服务注册"></a>服务注册</h2><p>　　既然采用了zookeeper做服务的自动注册功能，则需要开发一个连接zookeeper服务，并提供在zookeeper上创建节点的注册器，核心代码如下。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServiceRegistry</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> CountDownLatch      latch        = <span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>                 timeout      = <span class="number">5000</span>;</span><br><span class="line">    <span class="keyword">private</span> String              registerPath = <span class="string">"/registry"</span>;</span><br><span class="line">    <span class="keyword">private</span> String              zkAddress;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(String data)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (data != <span class="keyword">null</span>) &#123;</span><br><span class="line">            ZooKeeper zk = connectServer();</span><br><span class="line">            <span class="keyword">if</span> (zk != <span class="keyword">null</span>) &#123;</span><br><span class="line">                createNode(zk, data);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> ZooKeeper <span class="title">connectServer</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ZooKeeper zk = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            zk = <span class="keyword">new</span> ZooKeeper(zkAddress, timeout, <span class="keyword">new</span> Watcher() &#123;</span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">(WatchedEvent event)</span> </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (event.getState() == Event.KeeperState.SyncConnected) &#123;</span><br><span class="line">                        latch.countDown();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            latch.await();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            LogUtils.error(logger, <span class="string">"connectServer exception"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> zk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">createNode</span><span class="params">(ZooKeeper zk, String data)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">byte</span>[] bytes = data.getBytes();</span><br><span class="line">            <span class="comment">/**</span><br><span class="line">             * 创建一个节点，</span><br><span class="line">             * 第一个参数是该节点的路径，</span><br><span class="line">             * 第二个参数是该节点的初始化数据，</span><br><span class="line">             * 第三个参数是该节点的ACL，</span><br><span class="line">             * 第四个参数指定节点的创建策略</span><br><span class="line">             */</span></span><br><span class="line">            String createResult = zk.create(registerPath, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE,</span><br><span class="line">                CreateMode.EPHEMERAL_SEQUENTIAL);</span><br><span class="line">            LogUtils.info(logger, <span class="string">"创建的结果是：&#123;0&#125;"</span>, createResult);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            LogUtils.error(logger, <span class="string">"createNode exception"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　register方法的参数data包括了rpc服务的信息，这里指rpc服务的ip和port，形如：ip:port。我们会将rpc服务注册到zookeeper的/registry节点下，rpc服务的node类型为：CreateMode.EPHEMERAL_SEQUENTIAL。该类型的节点在会话结束后自动被删除，节点名末尾会自动追加一个10位数的单调递增的序号，这样可以达到rpc服务负载均衡的能力。</p>
<h2 id="u670D_u52A1_u53D1_u73B0"><a href="#u670D_u52A1_u53D1_u73B0" class="headerlink" title="服务发现"></a>服务发现</h2><p>　　有了服务注册的功能，我们再提供服务发现的功能。这样客户端在启动后，会调用该服务发现组件取rpc服务的连接信息，核心代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServiceDiscovery</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> CountDownLatch        latch    = <span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> List&lt;String&gt; dataList = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">    <span class="keyword">private</span> String zkAddress;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ZooKeeper zk = connectServer();</span><br><span class="line">        <span class="keyword">if</span> (zk != <span class="keyword">null</span>) &#123;</span><br><span class="line">            watchNode(zk);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">discover</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String data = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">int</span> size = dataList.size();</span><br><span class="line">        <span class="keyword">if</span> (size &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (size == <span class="number">1</span>) &#123;</span><br><span class="line">                data = dataList.get(<span class="number">0</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                data = dataList.get(ThreadLocalRandom.current().nextInt(size));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> data;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> ZooKeeper <span class="title">connectServer</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ZooKeeper zk = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            zk = <span class="keyword">new</span> ZooKeeper(zkAddress, <span class="number">5000</span>, <span class="keyword">new</span> Watcher() &#123;</span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">(WatchedEvent event)</span> </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (event.getState() == Event.KeeperState.SyncConnected) &#123;</span><br><span class="line">                        latch.countDown();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            latch.await();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> zk;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">watchNode</span><span class="params">(<span class="keyword">final</span> ZooKeeper zk)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            List&lt;String&gt; nodeList = zk.getChildren(<span class="string">"/"</span>, <span class="keyword">new</span> Watcher() &#123;</span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">(WatchedEvent event)</span> </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (event.getType() == Event.EventType.NodeChildrenChanged) &#123;</span><br><span class="line">                        watchNode(zk);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">            List&lt;String&gt; dataList = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">            <span class="keyword">for</span> (String node : nodeList) &#123;</span><br><span class="line">                System.out.println(<span class="string">"节点："</span> + node);</span><br><span class="line">                <span class="keyword">if</span>(node.startsWith(<span class="string">"registry"</span>))&#123;</span><br><span class="line">                    <span class="keyword">byte</span>[] bytes = zk.getData(<span class="string">"/"</span> + node, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">                    dataList.add(<span class="keyword">new</span> String(bytes));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.dataList = dataList;</span><br><span class="line">            <span class="keyword">if</span> (dataList.isEmpty()) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"尚未注册任何服务"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="u670D_u52A1_u6CE8_u89E3"><a href="#u670D_u52A1_u6CE8_u89E3" class="headerlink" title="服务注解"></a>服务注解</h2><p>　　这里我们定义一个注解RpcService，该注解作用于某个接口的实现类，指定该类为一个rpc服务接口。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Target</span>(&#123; ElementType.TYPE &#125;)</span><br><span class="line"><span class="annotation">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="annotation">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="annotation">@interface</span> RpcService &#123;</span><br><span class="line">    <span class="function">String <span class="title">value</span><span class="params">()</span> <span class="keyword">default</span> ""</span>;</span><br><span class="line">    Class&lt;?&gt; inf();<span class="comment">//服务提供者的接口类</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="PRC_u670D_u52A1_u63D0_u4F9B_u8005"><a href="#PRC_u670D_u52A1_u63D0_u4F9B_u8005" class="headerlink" title="PRC服务提供者"></a>PRC服务提供者</h2><p>　　下面介绍rpc服务最重要的的一个组件：服务提供者，核心代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RpcServer</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span>, <span class="title">InitializingBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String serverHostAndPort;</span><br><span class="line">    <span class="keyword">private</span> ServiceRegistry serviceRegistry;</span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, Object&gt; handlerMap = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        EventLoopGroup bossGroup = <span class="keyword">new</span> NioEventLoopGroup();</span><br><span class="line">        EventLoopGroup workerGroup = <span class="keyword">new</span> NioEventLoopGroup();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ServerBootstrap bootstrap = <span class="keyword">new</span> ServerBootstrap();</span><br><span class="line">            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)</span><br><span class="line">                    .childHandler(<span class="keyword">new</span> ChannelInitializer&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                        <span class="annotation">@Override</span></span><br><span class="line">                        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(SocketChannel channel)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                            channel.pipeline()</span><br><span class="line">                                    .addLast(<span class="keyword">new</span> RpcDecoder(RpcRequest.class)) <span class="comment">// 将 RPC 请求进行解码（为了处理请求）</span></span><br><span class="line">                                    .addLast(<span class="keyword">new</span> RpcEncoder(RpcResponse.class)) <span class="comment">// 将 RPC 响应进行编码（为了返回响应）</span></span><br><span class="line">                                    .addLast(<span class="keyword">new</span> RpcHandler(handlerMap)); <span class="comment">// 处理 RPC 请求</span></span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;).option(ChannelOption.SO_BACKLOG, <span class="number">128</span>)</span><br><span class="line">                    .childOption(ChannelOption.SO_KEEPALIVE, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">            String[] array = serverHostAndPort.split(<span class="string">":"</span>);</span><br><span class="line">            String host = array[<span class="number">0</span>];</span><br><span class="line">            <span class="keyword">int</span> port = Integer.parseInt(array[<span class="number">1</span>]);</span><br><span class="line"></span><br><span class="line">            ChannelFuture future = bootstrap.bind(host, port).sync();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (serviceRegistry != <span class="keyword">null</span>) &#123;</span><br><span class="line">                serviceRegistry.register(serverHostAndPort); <span class="comment">// 注册服务地址</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            future.channel().closeFuture().sync();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            workerGroup.shutdownGracefully();</span><br><span class="line">            bossGroup.shutdownGracefully();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext ctx)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        Map&lt;String, Object&gt; serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class); <span class="comment">// 获取所有带有 RpcService 注解的 Spring Bean</span></span><br><span class="line">        LogUtils.info(logger, <span class="string">"获取到所有的RPC服务有：&#123;0&#125;"</span>, serviceBeanMap);</span><br><span class="line">        <span class="keyword">if</span> (MapUtils.isNotEmpty(serviceBeanMap)) &#123;</span><br><span class="line">            <span class="keyword">for</span> (Object serviceBean : serviceBeanMap.values()) &#123;</span><br><span class="line">                String interfaceName = serviceBean.getClass().getAnnotation(RpcService.class).inf().getName();</span><br><span class="line">                handlerMap.put(interfaceName, serviceBean);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　该服务提供者在实现了spring的两个接口：ApplicationContextAware和InitializingBean，这样我们的spring容器启动后，首先会在setApplicationContext方法中获取到含有注解RpcService的类并解释，并放入一个HashMap中，这样接口和实现类的对应关系就建立了。该类中涉及到netty相关的知识不再做介绍，请直接下载示例代码！</p>
<h2 id="u5BA2_u6237_u7AEF_u4EE3_u7406"><a href="#u5BA2_u6237_u7AEF_u4EE3_u7406" class="headerlink" title="客户端代理"></a>客户端代理</h2><p>　　由于rpc调用的客户端，只存在服务的接口，这样就需要开发一个接口的代理工具。这样当我们调用接口的方法时，能够在代理方法中实现网络访问。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RpcProxyFactory</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String              serverAddress;</span><br><span class="line">    <span class="keyword">private</span> ServiceDiscovery    serviceDiscovery;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; <span class="function">T <span class="title">create</span><span class="params">(Class&lt;?&gt; interfaceClass)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(),</span><br><span class="line">            <span class="keyword">new</span> Class&lt;?&gt;[] &#123; interfaceClass &#125;, <span class="keyword">new</span> InvocationHandler() &#123;</span><br><span class="line"></span><br><span class="line">                <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">                    RpcRequest request = <span class="keyword">new</span> RpcRequest(); <span class="comment">// 创建并初始化 RPC 请求</span></span><br><span class="line">                    request.setRequestId(UUID.randomUUID().toString());</span><br><span class="line">                    request.setClassName(method.getDeclaringClass().getName());</span><br><span class="line">                    request.setMethodName(method.getName());</span><br><span class="line">                    request.setParameterTypes(method.getParameterTypes());</span><br><span class="line">                    request.setParameters(args);</span><br><span class="line">                    <span class="comment">//从ZK获取服务器的地址</span></span><br><span class="line">                    <span class="comment">// 如果服务发现不为空则主动发现服务，否则使用默认服务地址</span></span><br><span class="line">                    <span class="keyword">if</span> (serviceDiscovery != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        serverAddress = serviceDiscovery.discover(); <span class="comment">// 发现服务</span></span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">//服务的地址是host:port</span></span><br><span class="line">                    String[] array = serverAddress.split(<span class="string">":"</span>);</span><br><span class="line">                    String host = array[<span class="number">0</span>];</span><br><span class="line">                    <span class="keyword">int</span> port = Integer.parseInt(array[<span class="number">1</span>]);</span><br><span class="line"></span><br><span class="line">                    RpcClient client = <span class="keyword">new</span> RpcClient(host, port); <span class="comment">// 初始化 RPC 客户端</span></span><br><span class="line">                    RpcResponse response = client.send(request); <span class="comment">// 通过 RPC 客户端发送 RPC 请求并获取 RPC 响应</span></span><br><span class="line"></span><br><span class="line">                    <span class="keyword">if</span> (response.isError()) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> response.getError();</span><br><span class="line">                    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                        <span class="keyword">return</span> response.getResult();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　在代理方法中，我们将调用的接口类、方法和参数等信息封装到RpcRequest中。最后我们构造了一个RpcClient对象，向服务端发送调用请求，下面我们看看RpcClient的实现：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RpcClient</span> <span class="keyword">extends</span> <span class="title">SimpleChannelInboundHandler</span>&lt;<span class="title">RpcResponse</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String       host;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>          port;</span><br><span class="line">    <span class="keyword">private</span> RpcResponse  response;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Object obj = <span class="keyword">new</span> Object();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">RpcClient</span><span class="params">(String host, <span class="keyword">int</span> port)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.host = host;</span><br><span class="line">        <span class="keyword">this</span>.port = port;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RpcResponse <span class="title">send</span><span class="params">(RpcRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        EventLoopGroup group = <span class="keyword">new</span> NioEventLoopGroup();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Bootstrap bootstrap = <span class="keyword">new</span> Bootstrap();</span><br><span class="line">            bootstrap.group(group).channel(NioSocketChannel.class)</span><br><span class="line">                .handler(<span class="keyword">new</span> ChannelInitializer&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                    <span class="annotation">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(SocketChannel channel)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                        channel.pipeline().addLast(<span class="keyword">new</span> RpcEncoder(RpcRequest.class)) <span class="comment">// 将 RPC 请求进行编码（为了发送请求）</span></span><br><span class="line">                            .addLast(<span class="keyword">new</span> RpcDecoder(RpcResponse.class)) <span class="comment">// 将 RPC 响应进行解码（为了处理响应）</span></span><br><span class="line">                            .addLast(RpcClient.<span class="keyword">this</span>); <span class="comment">// 使用 RpcClient 发送 RPC 请求</span></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;).option(ChannelOption.SO_KEEPALIVE, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">            ChannelFuture future = bootstrap.connect(host, port).sync();</span><br><span class="line">            future.channel().writeAndFlush(request).sync();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">synchronized</span> (obj) &#123;</span><br><span class="line">                obj.wait(); <span class="comment">// 未收到响应，使线程等待</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (response != <span class="keyword">null</span>) &#123;</span><br><span class="line">                future.channel().closeFuture().sync();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> response;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            group.shutdownGracefully();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead0</span><span class="params">(ChannelHandlerContext ctx, RpcResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.response = response;</span><br><span class="line">        <span class="keyword">synchronized</span> (obj) &#123;</span><br><span class="line">            obj.notifyAll(); <span class="comment">// 收到响应，唤醒线程</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　注意该代码，由于这里采用的nio的实现，调用send方法后，如果不做特殊的处理，代码会立刻返回。所以这里需要重点关注成员变量obj的wait和notifyAll方法的巧妙使用。</p>
<h2 id="Protostuff"><a href="#Protostuff" class="headerlink" title="Protostuff"></a>Protostuff</h2><p>　　Protostuff是基于大名鼎鼎的Google protobuff技术的Java版本，直接使用原生的protobuff是需要数据结构的预编译过程，需要编写.proto格式的配置文件，再通过protobuf提供的工具翻译成目标语言代码，而Protostuff动态支持了protobuff的预编译的过程。使用Protostuff，我们不需要定义任何.proto格式的配置文件，这里提供了一个Protostuff的工具类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ProtostuffSerializationUtil</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Map&lt;Class&lt;?&gt;, Schema&lt;?&gt;&gt; cachedSchema = <span class="keyword">new</span> ConcurrentHashMap&lt;Class&lt;?&gt;, Schema&lt;?&gt;&gt;();</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Objenesis objenesis = <span class="keyword">new</span> ObjenesisStd(<span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">Schema&lt;T&gt; <span class="title">getSchema</span><span class="params">(Class&lt;T&gt; clazz)</span> </span>&#123;</span><br><span class="line">        <span class="annotation">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">        Schema&lt;T&gt; schema = (Schema&lt;T&gt;) cachedSchema.get(clazz);</span><br><span class="line">        <span class="keyword">if</span> (schema == <span class="keyword">null</span>) &#123;</span><br><span class="line">            schema = RuntimeSchema.getSchema(clazz);</span><br><span class="line">            <span class="keyword">if</span> (schema != <span class="keyword">null</span>) &#123;</span><br><span class="line">                cachedSchema.put(clazz, schema);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> schema;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="keyword">byte</span>[] serializer(T obj) &#123;</span><br><span class="line">        <span class="annotation">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">        Class&lt;T&gt; clazz = (Class&lt;T&gt;) obj.getClass();</span><br><span class="line">        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Schema&lt;T&gt; schema = getSchema(clazz);</span><br><span class="line">            <span class="keyword">return</span> ProtostuffIOUtil.toByteArray(obj, schema, buffer);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(e.getMessage(), e);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            buffer.clear();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">deserializer</span><span class="params">(<span class="keyword">byte</span>[] data, Class&lt;T&gt; clazz)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            T obj = objenesis.newInstance(clazz);</span><br><span class="line">            Schema&lt;T&gt; schema = getSchema(clazz);</span><br><span class="line">            ProtostuffIOUtil.mergeFrom(data, obj, schema);</span><br><span class="line">            <span class="keyword">return</span> obj;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(e.getMessage(), e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="RpcRequest_u3001RpcResponse"><a href="#RpcRequest_u3001RpcResponse" class="headerlink" title="RpcRequest、RpcResponse"></a>RpcRequest、RpcResponse</h2><p>　　每次调用过程，都需要封装请求参数，返回的结果也需要封装，我们定义两个实体类进行封装<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RpcRequest</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 请求Id</span></span><br><span class="line">    <span class="keyword">private</span> String     requestId;</span><br><span class="line">    <span class="comment">// 远程调用类名称</span></span><br><span class="line">    <span class="keyword">private</span> String     className;</span><br><span class="line">    <span class="comment">//远程调用方法名称</span></span><br><span class="line">    <span class="keyword">private</span> String     methodName;</span><br><span class="line">    <span class="comment">// 参数类型</span></span><br><span class="line">    <span class="keyword">private</span> Class&lt;?&gt;[] parameterTypes;</span><br><span class="line">    <span class="comment">// 参数值</span></span><br><span class="line">    <span class="keyword">private</span> Object[]   parameters;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RpcResponse</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 请求的Id</span></span><br><span class="line">    <span class="keyword">private</span> String    requestId;</span><br><span class="line">    <span class="comment">// 异常</span></span><br><span class="line">    <span class="keyword">private</span> Throwable error;</span><br><span class="line">    <span class="comment">// 响应</span></span><br><span class="line">    <span class="keyword">private</span> Object    result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　到这里我们基本上即介绍完了，注意该示例采用的是短连接，实际上，优秀的rpc框架，如dubbo，thrift等都是采用tcp长连接的。源码下载地址：<a href="/code/rpc-netty-zk.zip">rpc-netty-zk.zip</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/01/rpc/16.RPC系列之基于Netty、ZK的实现原型/" data-id="cijzzpv43002v1cfs5f0bu6un" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/commonjs/">commonjs</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/rpc/">rpc</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/4.AOP系列之CGLIB" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/01/java/4.AOP系列之CGLIB/" class="article-date">
  <time datetime="2015-12-01T07:21:36.000Z" itemprop="datePublished">2015-12-01</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/01/java/4.AOP系列之CGLIB/">AOP系列四之CGLIB</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　CGLIB包的底层是通过使用一个小而快的字节码处理框架ASM(Java字节码操控框架)，来转换字节码并生成新的子类，并将切面逻辑加入到子类中（动态字节码生成技术），所以使用Cglib实现AOP不需要基于接口。除了CGLIB包，脚本语言例如 Groovy和BeanShell，也是使用ASM来生成java的字节码。不鼓励直接使用ASM，因为它要求你必须对JVM内部结构包括class文件的格式和指令集都很熟悉。所以cglib包要依赖于asm包，需要一起导入。下图为cglib与一些框架和语言的关系（CGLIB Library and ASM Bytecode Framework）。</p>
<p><img src="/images/cglib-structure.gif" alt="cglib-structure.gif"></p>
<h2 id="u793A_u4F8B"><a href="#u793A_u4F8B" class="headerlink" title="示例"></a>示例</h2><p>　　JDK实现动态代理需要实现类通过接口定义业务方法，对于没有接口的类，如何实现动态代理呢，这就需要CGLib了。CGLib采用了非常底层的字节码技术，其原理是通过字节码技术为一个类创建子类，并在子类中采用方法拦截的技术拦截所有父类方法的调用，顺势织入横切逻辑。JDK动态代理与CGLib动态代理均是实现Spring AOP的基础。</p>
<p>对类进行代理<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CglibProxyDemo</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, <span class="string">"C:/class"</span>);</span><br><span class="line">        CglibProxy proxy = <span class="keyword">new</span> CglibProxy();</span><br><span class="line">        <span class="comment">//通过生成子类的方式创建代理类</span></span><br><span class="line">        SayHello proxyImp = (SayHello)proxy.getProxy(SayHello.class);</span><br><span class="line">        proxyImp.say();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//定义一个被代理的父类</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">SayHello</span> </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">say</span><span class="params">()</span></span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"hello everyone"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">CglibProxy</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> Enhancer enhancer = <span class="keyword">new</span> Enhancer();</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">(Class clazz)</span></span>&#123;</span><br><span class="line">            <span class="comment">//设置需要创建子类的类</span></span><br><span class="line">            enhancer.setSuperclass(clazz);</span><br><span class="line">            enhancer.setCallback(<span class="keyword">this</span>);</span><br><span class="line">            <span class="comment">//通过字节码技术动态创建子类实例</span></span><br><span class="line">            <span class="keyword">return</span> enhancer.create();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="annotation">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object obj, Method method, Object[] args,</span><br><span class="line">                                MethodProxy proxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"前置代理"</span>);</span><br><span class="line">            <span class="comment">//通过代理类调用父类中的方法</span></span><br><span class="line">            Object result = proxy.invokeSuper(obj, args);</span><br><span class="line">            System.out.println(<span class="string">"后置代理"</span>);</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>对接口进行代理<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CglibProxyDemo2</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, <span class="string">"C:/class"</span>);</span><br><span class="line">        CglibProxy proxy = <span class="keyword">new</span> CglibProxy();</span><br><span class="line"></span><br><span class="line">        ISayHello proxyImp = (ISayHello)proxy.getProxy(ISayHello.class);</span><br><span class="line">        proxyImp.say();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">interface</span> <span class="title">ISayHello</span> </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">void</span> <span class="title">say</span><span class="params">()</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">CglibProxy</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> Enhancer enhancer = <span class="keyword">new</span> Enhancer();</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">(Class clazz)</span></span>&#123;</span><br><span class="line">            <span class="comment">//设置需要创建子类的类</span></span><br><span class="line">            enhancer.setSuperclass(clazz);</span><br><span class="line">            enhancer.setCallback(<span class="keyword">this</span>);</span><br><span class="line">            <span class="comment">//通过字节码技术动态创建子类实例</span></span><br><span class="line">            <span class="keyword">return</span> enhancer.create();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="annotation">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object obj, Method method, Object[] args,</span><br><span class="line">                                MethodProxy proxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"前置代理"</span>);</span><br><span class="line">            <span class="comment">//此时代理的为接口，不可调用</span></span><br><span class="line">            <span class="comment">//Object result = proxy.invokeSuper(obj, args);</span></span><br><span class="line">            System.out.println(<span class="string">"后置代理"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="u5B9E_u73B0_u539F_u7406"><a href="#u5B9E_u73B0_u539F_u7406" class="headerlink" title="实现原理"></a>实现原理</h2><p>　　在上面的代码中，通过System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, “C:/class”);语句，将Cglib动态生成的字节码保存到本地并且反编译查看，或者通过调试的方式（详见下图），可以看出，Cglib是通过动态创建子类的方式进行动态代理，在这点上，与JDK的方式一样。<br><img src="/images/cglib-proxy.png" alt="cglib-proxy"></p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　CGLib创建的动态代理对象性能比JDK创建的动态代理对象的性能高不少，但是CGLib在创建代理对象时所花费的时间却比JDK多得多，所以对于单例的对象，因为无需频繁创建对象，用CGLib合适，反之，使用JDK方式要更为合适一些。同时，由于CGLib由于是采用动态创建子类的方法，对于final方法，无法进行代理。</p>
<h2 id="u7CFB_u5217_u6587_u7AE0"><a href="#u7CFB_u5217_u6587_u7AE0" class="headerlink" title="系列文章"></a>系列文章</h2><p><a href="/../1.AOP系列之概述/">1. AOP系列之概述</a><br><a href="/../2.AOP系列之AspectJ/">2. AOP系列之AspectJ</a><br><a href="/../3.AOP系列之JDK Proxy/">3. AOP系列之JDK Proxy</a><br><a href="/../4.AOP系列之CGLIB/">4. AOP系列之CGLIB</a><br><a href="/../5.AOP系列之CGLIB源码学习/">5. AOP系列之CGLIB源码学习</a><br><a href="/../6.AOP系列之Spring AOP/">6. AOP系列之Spring AOP</a><br><a href="/../7.AOP系列之Spring AspectJ/">7. AOP系列之Spring AspectJ</a></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://blog.csdn.net/xiaohai0504/article/details/6832990" target="_blank" rel="external">http://blog.csdn.net/xiaohai0504/article/details/6832990</a><br><a href="http://blog.csdn.net/xiaohai0504/article/details/6833822" target="_blank" rel="external">http://blog.csdn.net/xiaohai0504/article/details/6833822</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/01/java/4.AOP系列之CGLIB/" data-id="cijzzpvdm00cr1cfsxfen4tpd" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/aop/">aop</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/gclib/">gclib</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/3.AOP系列之JDK Proxy" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/01/java/3.AOP系列之JDK Proxy/" class="article-date">
  <time datetime="2015-12-01T06:21:36.000Z" itemprop="datePublished">2015-12-01</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/01/java/3.AOP系列之JDK Proxy/">AOP系列三之JDK Proxy</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　什么是动态代理：说起动态，其实不如先说什么是静态。所谓静态代理，个人理解为自己手写的代理类，或者用工具生成的代理类，或者别人帮你写的代理类(没说一样…)。总之，就是程序运行前就已经存在的编译好的代理类。相反，如果代理类程序运行前并不存在，需要在程序运行时动态生成(无需手工编写代理类源码)，那就是今天要说的动态代理了。</p>
<h2 id="u793A_u4F8B"><a href="#u793A_u4F8B" class="headerlink" title="示例"></a>示例</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.reflect.InvocationHandler;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Proxy;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JDKProxy</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">        InvokerImpl invokerImpl = <span class="keyword">new</span> InvokerImpl();</span><br><span class="line">        Invoker invoker = (Invoker)Proxy.newProxyInstance(</span><br><span class="line">                                        JDKProxy.class.getClassLoader(),</span><br><span class="line">                                        <span class="comment">//该参数必须为接口，方法内存在该参数类型校验</span></span><br><span class="line">                                        <span class="keyword">new</span> Class[]&#123;Invoker.class&#125;,</span><br><span class="line">                                        <span class="keyword">new</span> JDKInvocationHandler(invokerImpl));</span><br><span class="line">        invoker.process();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Invoker</span> </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">void</span> <span class="title">process</span><span class="params">()</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">InvokerImpl</span> <span class="keyword">implements</span> <span class="title">Invoker</span> </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">()</span></span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"方法被执行了"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">JDKInvocationHandler</span> <span class="keyword">implements</span> <span class="title">InvocationHandler</span></span>&#123;</span><br><span class="line">        <span class="keyword">private</span> Object proxied;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">JDKInvocationHandler</span><span class="params">(Object proxied)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.proxied = proxied;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="annotation">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"额外的逻辑被执行了"</span>);</span><br><span class="line">            <span class="keyword">return</span> method.invoke(proxied, args);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="u5B9E_u73B0_u539F_u7406"><a href="#u5B9E_u73B0_u539F_u7406" class="headerlink" title="实现原理"></a>实现原理</h2><p>　　看到上面代码，我们产生了几个疑问，首先，JDK的动态代理实现的原理是什么呢，同时在调用接口Invoker的process()方法的时候，为什么会执行InvocationHandler的invoke方法。下面我们带着这些疑问进入jdk的动态代理实现源码一探究竟<br>　　首先进入Proxy.newProxyInstance的实现，可以看到最核心的三行代码<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Class&lt;?&gt; cl = getProxyClass(loader, interfaces);</span><br><span class="line">Constructor cons = cl.getConstructor(constructorParams);</span><br><span class="line"><span class="keyword">return</span> cons.newInstance(<span class="keyword">new</span> Object[] &#123; h &#125;);</span><br></pre></td></tr></table></figure></p>
<p>　　首先根据传入接口和classloader(通过调试，可以发现该classloader为Launcher$AppClassLoader)生成一个代理类，然后返回该代理类的一个实例，程序通过该实例实现了动态代理（那么该实例应该实现了接口的所有方法）。那么该代理类是如何生成实现的呢？下面我们进入getProxyClass方法查找原因。<br>　　在getProxyClass方法中，有两行关键的代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">byte</span>[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces);</span><br><span class="line">proxyClass = defineClass0(loader, proxyName, proxyClassFile, <span class="number">0</span>, proxyClassFile.length);</span><br></pre></td></tr></table></figure></p>
<p>　　可以看到通过ProxyGenerator.generateProxyClass生成了代理类的二进制码，再通过native方法defineClass0生成了代理类，最后返回该代理类，那么该代理类到底是如何实现的呢，下面我们可以通过以下几行代码将byte[]类型的proxyClassFile写入到磁盘的.class文件中，并反编译该class文件一探究竟<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">String name = <span class="string">"InvokerSubject"</span>;</span><br><span class="line"><span class="keyword">byte</span>[] data = ProxyGenerator.generateProxyClass( name, <span class="keyword">new</span> Class[] &#123; Invoker.class &#125; );</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">	FileOutputStream out = <span class="keyword">new</span> FileOutputStream( name + <span class="string">".class"</span> );</span><br><span class="line">	out.write( data );</span><br><span class="line">	out.close();</span><br><span class="line">&#125; <span class="keyword">catch</span>( Exception e ) &#123;</span><br><span class="line">	e.printStackTrace();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　反编译后代码如下<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> JDKProxy.Invoker;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.InvocationHandler;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Proxy;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.UndeclaredThrowableException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ProxySubject</span> <span class="keyword">extends</span> <span class="title">Proxy</span> <span class="keyword">implements</span> <span class="title">Invoker</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m1;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m3;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m0;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Method m2;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ProxySubject</span><span class="params">(InvocationHandler var1)</span> <span class="keyword">throws</span>  </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(var1);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object var1)</span> <span class="keyword">throws</span>  </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> ((Boolean)<span class="keyword">super</span>.h.invoke(<span class="keyword">this</span>, m1, <span class="keyword">new</span> Object[]&#123;var1&#125;)).booleanValue();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var3;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var4) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UndeclaredThrowableException(var4);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">()</span> <span class="keyword">throws</span>  </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">super</span>.h.invoke(<span class="keyword">this</span>, m3, (Object[])<span class="keyword">null</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var2;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UndeclaredThrowableException(var3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">hashCode</span><span class="params">()</span> <span class="keyword">throws</span>  </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> ((Integer)<span class="keyword">super</span>.h.invoke(<span class="keyword">this</span>, m0, (Object[])<span class="keyword">null</span>)).intValue();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var2;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UndeclaredThrowableException(var3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> String <span class="title">toString</span><span class="params">()</span> <span class="keyword">throws</span>  </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (String)<span class="keyword">super</span>.h.invoke(<span class="keyword">this</span>, m2, (Object[])<span class="keyword">null</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var2;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UndeclaredThrowableException(var3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            m1 = Class.forName(<span class="string">"java.lang.Object"</span>).getMethod(<span class="string">"equals"</span>, <span class="keyword">new</span> Class[]&#123;Class.forName(<span class="string">"java.lang.Object"</span>)&#125;);</span><br><span class="line">            m3 = Class.forName(<span class="string">"JDKProxy$Invoker"</span>).getMethod(<span class="string">"process"</span>, <span class="keyword">new</span> Class[<span class="number">0</span>]);</span><br><span class="line">            m0 = Class.forName(<span class="string">"java.lang.Object"</span>).getMethod(<span class="string">"hashCode"</span>, <span class="keyword">new</span> Class[<span class="number">0</span>]);</span><br><span class="line">            m2 = Class.forName(<span class="string">"java.lang.Object"</span>).getMethod(<span class="string">"toString"</span>, <span class="keyword">new</span> Class[<span class="number">0</span>]);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchMethodException var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchMethodError(var2.getMessage());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ClassNotFoundException var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NoClassDefFoundError(var3.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　首先该代理类实现了Invoker接口，同时也继承了java.lang.reflect.Proxy类，这也就解释了为什么JDK的动态代理必须为接口的原因。在process方法中，调用了JDKInvocationHandler的invoke方法。到这里JDK动态代理的原理也就明晰了！ProxyGenerator内部是如何生成class二进制数据，可以参考源代码。</p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　一个典型的动态代理创建对象过程可分为以下四个步骤：</p>
<ol>
<li>通过实现InvocationHandler接口创建自己的调用处理器InvocationHandler handler = new InvocationHandlerImpl(…);</li>
<li>通过为Proxy类指定ClassLoader对象和一组interface创建动态代理类<br>Class clazz = Proxy.getProxyClass(classLoader,new Class[]{…});</li>
<li>通过反射机制获取动态代理类的构造函数，其参数类型是调用处理器接口类型<br>Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.class});</li>
<li>通过构造函数创建代理类实例，此时需将调用处理器对象作为参数被传入<br>Interface Proxy = (Interface)constructor.newInstance(new Object[] (handler));<br> 为了简化对象创建过程，Proxy类中的newInstance方法封装了2~4步，只需两步即可完成代理对象的创建。生成的InvokerSubject继承Proxy类实现Subject接口，实现的Subject的方法实际调用处理器的invoke方法，而invoke方法利用反射调用的是被代理对象的的方法（Object result=method.invoke(proxied,args)）</li>
</ol>
<h2 id="u7F3A_u70B9"><a href="#u7F3A_u70B9" class="headerlink" title="缺点"></a>缺点</h2><p>　　诚然，Proxy已经设计得非常优美，但是还是有一点点小小的遗憾之处，那就是它始终无法摆脱仅支持interface代理的桎梏，因为它的设计注定了这个遗憾。回想一下那些动态生成的代理类的继承关系图，它们已经注定有一个共同的父类叫Proxy。Java的继承机制注定了这些动态代理类们无法实现对class的动态代理，原因是多继承在Java中本质上就行不通。有很多条理由，人们可以否定对 class代理的必要性，但是同样有一些理由，相信支持class动态代理会更美好。接口和类的划分，本就不是很明显，只是到了Java中才变得如此的细化。如果只从方法的声明及是否被定义来考量，有一种两者的混合体，它的名字叫抽象类。实现对抽象类的动态代理，相信也有其内在的价值。此外，还有一些历史遗留的类，它们将因为没有实现任何接口而从此与动态代理永世无缘。如此种种，不得不说是一个小小的遗憾。但是，不完美并不等于不伟大，伟大是一种本质，Java动态代理就是佐例。</p>
<h2 id="u7CFB_u5217_u6587_u7AE0"><a href="#u7CFB_u5217_u6587_u7AE0" class="headerlink" title="系列文章"></a>系列文章</h2><p><a href="/../1.AOP系列之概述/">1. AOP系列之概述</a><br><a href="/../2.AOP系列之AspectJ/">2. AOP系列之AspectJ</a><br><a href="/../3.AOP系列之JDK Proxy/">3. AOP系列之JDK Proxy</a><br><a href="/../4.AOP系列之CGLIB/">4. AOP系列之CGLIB</a><br><a href="/../5.AOP系列之CGLIB源码学习/">5. AOP系列之CGLIB源码学习</a><br><a href="/../6.AOP系列之Spring AOP/">6. AOP系列之Spring AOP</a><br><a href="/../7.AOP系列之Spring AspectJ/">7. AOP系列之Spring AspectJ</a></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://www.ibm.com/developerworks/cn/java/j-lo-proxy1/index.html" target="_blank" rel="external">http://www.ibm.com/developerworks/cn/java/j-lo-proxy1/index.html</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/01/java/3.AOP系列之JDK Proxy/" data-id="cijzzpvdq00cw1cfsrleiq0j3" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/aop/">aop</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/proxy/">proxy</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-rpc/14.RPC系列之CommonJS协议分析" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2015/12/01/rpc/14.RPC系列之CommonJS协议分析/" class="article-date">
  <time datetime="2015-12-01T06:00:00.000Z" itemprop="datePublished">2015-12-01</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/rpc/">rpc</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2015/12/01/rpc/14.RPC系列之CommonJS协议分析/">RPC系列十四之CommonJS 协议分析</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2015/12/01/rpc/14.RPC系列之CommonJS协议分析/" data-id="cijzzpv4h00311cfslvz0pvvd" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/commonjs/">commonjs</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/rpc/">rpc</a></li></ul>

    </footer>
  </div>
  
</article>


  
  
    <nav id="page-nav">
      <a class="extend prev" rel="prev" href="/page/12/">&laquo; Prev</a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/11/">11</a><a class="page-number" href="/page/12/">12</a><span class="page-number current">13</span><a class="page-number" href="/page/14/">14</a><a class="page-number" href="/page/15/">15</a><a class="extend next" rel="next" href="/page/14/">Next &raquo;</a>
    </nav>
  
</section>
        
          <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/cache/">cache</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/database/">database</a><span class="category-list-count">13</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/docker/">docker</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/gis/">gis</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/git/">git</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/go/">go</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/gradle/">gradle</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/groovy/">groovy</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/hadoop/">hadoop</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/java/">java</a><span class="category-list-count">18</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/linux/">linux</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/log/">log</a><span class="category-list-count">11</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mongodb/">mongodb</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mq/">mq</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mybatis/">mybatis</a><span class="category-list-count">9</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/netty/">netty</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nginx/">nginx</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nio/">nio</a><span class="category-list-count">19</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nodejs/">nodejs</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/redis/">redis</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/rpc/">rpc</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/spring/">spring</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/tomcat/">tomcat</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/zookeeper/">zookeeper</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/杂项/">杂项</a><span class="category-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/aop/">aop</a><span class="tag-list-count">8</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/aspectj/">aspectj</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/cache/">cache</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/classloader/">classloader</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/common-loggings/">common-loggings</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/commonjs/">commonjs</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/database/">database</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/docker/">docker</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/dubbo/">dubbo</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/fastdfs/">fastdfs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gclib/">gclib</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/geohash/">geohash</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gis/">gis</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/">git</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/go/">go</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gradle/">gradle</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/groovy/">groovy</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hadoop/">hadoop</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hessisan/">hessisan</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/">java</a><span class="tag-list-count">48</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/javassist/">javassist</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/kafka/">kafka</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/linux/">linux</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/log/">log</a><span class="tag-list-count">11</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/log4j/">log4j</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/logback/">logback</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/map/">map</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/memecached/">memecached</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mina/">mina</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mongodb/">mongodb</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mq/">mq</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mqtt/">mqtt</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mybatis/">mybatis</a><span class="tag-list-count">9</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/netty/">netty</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nginx/">nginx</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nio/">nio</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nodejs/">nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/postgresql/">postgresql</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/protobuf/">protobuf</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/proxy/">proxy</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/push/">push</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rabbitmq/">rabbitmq</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/redis/">redis</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rpc/">rpc</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sitemesh/">sitemesh</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sld/">sld</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/slf4j/">slf4j</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/socket/">socket</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spatialite-for-android/">spatialite for android</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spi/">spi</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spring/">spring</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/tomcat/">tomcat</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/transaction/">transaction</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/web/">web</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/xSocket/">xSocket</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zbus/">zbus</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zookeeper/">zookeeper</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/数据结构/">数据结构</a><span class="tag-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/aop/" style="font-size: 15.38px;">aop</a> <a href="/tags/aspectj/" style="font-size: 11.54px;">aspectj</a> <a href="/tags/cache/" style="font-size: 11.54px;">cache</a> <a href="/tags/classloader/" style="font-size: 10px;">classloader</a> <a href="/tags/common-loggings/" style="font-size: 10px;">common-loggings</a> <a href="/tags/commonjs/" style="font-size: 12.31px;">commonjs</a> <a href="/tags/database/" style="font-size: 16.92px;">database</a> <a href="/tags/docker/" style="font-size: 13.85px;">docker</a> <a href="/tags/dubbo/" style="font-size: 10px;">dubbo</a> <a href="/tags/fastdfs/" style="font-size: 10px;">fastdfs</a> <a href="/tags/gclib/" style="font-size: 10.77px;">gclib</a> <a href="/tags/geohash/" style="font-size: 10px;">geohash</a> <a href="/tags/gis/" style="font-size: 10px;">gis</a> <a href="/tags/git/" style="font-size: 10.77px;">git</a> <a href="/tags/go/" style="font-size: 10px;">go</a> <a href="/tags/gradle/" style="font-size: 10px;">gradle</a> <a href="/tags/groovy/" style="font-size: 10px;">groovy</a> <a href="/tags/hadoop/" style="font-size: 10px;">hadoop</a> <a href="/tags/hessisan/" style="font-size: 11.54px;">hessisan</a> <a href="/tags/java/" style="font-size: 20px;">java</a> <a href="/tags/javassist/" style="font-size: 10px;">javassist</a> <a href="/tags/kafka/" style="font-size: 11.54px;">kafka</a> <a href="/tags/linux/" style="font-size: 12.31px;">linux</a> <a href="/tags/log/" style="font-size: 17.69px;">log</a> <a href="/tags/log4j/" style="font-size: 12.31px;">log4j</a> <a href="/tags/logback/" style="font-size: 13.08px;">logback</a> <a href="/tags/map/" style="font-size: 10px;">map</a> <a href="/tags/memecached/" style="font-size: 10.77px;">memecached</a> <a href="/tags/mina/" style="font-size: 13.08px;">mina</a> <a href="/tags/mongodb/" style="font-size: 19.23px;">mongodb</a> <a href="/tags/mq/" style="font-size: 13.85px;">mq</a> <a href="/tags/mqtt/" style="font-size: 10.77px;">mqtt</a> <a href="/tags/mybatis/" style="font-size: 16.15px;">mybatis</a> <a href="/tags/netty/" style="font-size: 10px;">netty</a> <a href="/tags/nginx/" style="font-size: 11.54px;">nginx</a> <a href="/tags/nio/" style="font-size: 13.08px;">nio</a> <a href="/tags/nodejs/" style="font-size: 10px;">nodejs</a> <a href="/tags/postgresql/" style="font-size: 10.77px;">postgresql</a> <a href="/tags/protobuf/" style="font-size: 10px;">protobuf</a> <a href="/tags/proxy/" style="font-size: 10px;">proxy</a> <a href="/tags/push/" style="font-size: 10px;">push</a> <a href="/tags/rabbitmq/" style="font-size: 11.54px;">rabbitmq</a> <a href="/tags/redis/" style="font-size: 13.85px;">redis</a> <a href="/tags/rpc/" style="font-size: 19.23px;">rpc</a> <a href="/tags/sitemesh/" style="font-size: 10px;">sitemesh</a> <a href="/tags/sld/" style="font-size: 10px;">sld</a> <a href="/tags/slf4j/" style="font-size: 10px;">slf4j</a> <a href="/tags/socket/" style="font-size: 14.62px;">socket</a> <a href="/tags/spatialite-for-android/" style="font-size: 10px;">spatialite for android</a> <a href="/tags/spi/" style="font-size: 10px;">spi</a> <a href="/tags/spring/" style="font-size: 18.46px;">spring</a> <a href="/tags/tomcat/" style="font-size: 10.77px;">tomcat</a> <a href="/tags/transaction/" style="font-size: 10px;">transaction</a> <a href="/tags/web/" style="font-size: 10px;">web</a> <a href="/tags/xSocket/" style="font-size: 14.62px;">xSocket</a> <a href="/tags/zbus/" style="font-size: 10px;">zbus</a> <a href="/tags/zookeeper/" style="font-size: 10.77px;">zookeeper</a> <a href="/tags/数据结构/" style="font-size: 10.77px;">数据结构</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/01/">January 2016</a><span class="archive-list-count">67</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/12/">December 2015</a><span class="archive-list-count">81</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/11/">November 2015</a><span class="archive-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recents</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2016/01/30/资料/">(no title)</a>
          </li>
        
          <li>
            <a href="/2016/01/30/java/13.Classloader系列一/">ClassLoader系列一</a>
          </li>
        
          <li>
            <a href="/2016/01/29/hadoop/1.hadoop系列之源码编译/">hadoop系列一之源码编译</a>
          </li>
        
          <li>
            <a href="/2016/01/29/go/1.GO系列之入门/">Go系列一之入门</a>
          </li>
        
          <li>
            <a href="/2016/01/28/tomcat/2.tomcat性能优化/">tomcat性能优化</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2016 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>